Timer

Option

Click Extra can measure the execution time of a CLI via a dedicated --time/--no-time option.

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: 299.022872325
Execution time: 0.000 seconds.

click_extra.timer API

        classDiagram
  ExtraOption <|-- TimerOption
    

… py:module:: click_extra.timer

Command execution time measurement.

… py:class:: TimerOption(param_decls=None, default=False, expose_value=False, is_eager=True, help=‘Measure and print elapsed execution time.’, **kwargs)

module:

click_extra.timer

Bases: :py:class:~click_extra.parameters.ExtraOption

A pre-configured option that is adding a --time/--no-time flag to print elapsed time at the end of CLI execution.

The start time is made available in the context in ctx.meta["click_extra.start_time"].

… py:method:: TimerOption.print_timer()

module:

click_extra.timer

Compute and print elapsed execution time.

rtype:

:sphinx_autodoc_typehints_type:\:py\:obj\:\None``

… py:method:: TimerOption.register_timer_on_close(ctx, param, value)

module:

click_extra.timer

Callback setting up all timer’s machinery.

Computes and print the execution time at the end of the CLI, if option has been activated.

rtype:
sphinx_autodoc_typehints_type:

\:py\:obj\:\None``