Timer¶
Option¶
Click Extra can measure the execution time of a CLI via a dedicated --time/--no-time option.
Tip
When --time is enabled, the time.perf_counter() snapshot taken at startup is published on ctx.meta as START_TIME. See the available keys table to read it from your own callbacks.
Here how to use the standalone decorator:
from time import sleep
from click import command, echo, pass_context
from click_extra import timer_option
@command
@timer_option
def timer():
sleep(0.2)
echo("Hello world!")
$ timer --help
Usage: timer [OPTIONS]
Options:
--time / --no-time Measure and print elapsed execution time.
--help Show this message and exit.
$ timer --time
Hello world!
Execution time: 0.200 seconds.
Get start time¶
You can get the timestamp of the CLI start from the context:
from click import command, echo, pass_context
from click_extra import timer_option
@command
@timer_option
@pass_context
def timer_command(ctx):
start_time = ctx.meta["click_extra.start_time"]
echo(f"Start timestamp: {start_time}")
$ timer --time
Start timestamp: 91.849149155
Execution time: 0.000 seconds.
click_extra.timer API¶
classDiagram
ExtraOption <|-- TimerOption
Command execution time measurement.
- class click_extra.timer.TimerOption(param_decls=None, default=False, expose_value=False, is_eager=True, help='Measure and print elapsed execution time.', **kwargs)[source]¶
Bases:
ExtraOptionA pre-configured option that is adding a
--time/--no-timeflag to print elapsed time at the end of CLI execution.The start time is made available in the context in
ctx.meta[click_extra.context.START_TIME].- print_timer()[source]¶
Compute and print elapsed execution time.
Always prints, even when a sibling eager option (
--version,--show-params,--show-config…) short-circuited the command body viactx.exit(). That makes--timea usable probe for the cost of Click Extra’s own machinery (option parsing, config loading, eager callbacks), not just user command bodies.- Return type:
- init_timer(ctx, param, value)[source]¶
Set up the execution-timer machinery for the current invocation.
Captures
time.perf_counter()as the start time, stores it onctx.metaunderclick_extra.context.START_TIME, and queuesprint_timer()as a context-close callback so the elapsed duration is printed even when a sibling eager option (--version,--show-params…) short-circuits the command body.Renamed from
register_timer_on_closeto align with theinit_<system>convention shared withinit_formatterandinit_sort.- Return type: