lair.clock.Timer#

class lair.clock.Timer(name=None, text='Elapsed time: {:0.4f} seconds', logger=<built-in function print>)[source]#

Bases: ContextDecorator

Time your code using a class, context manager, or decorator

https://realpython.com/python-timer

Parameters:
  • name (str, optional) – A name to add the elapsed times up under, in the class’s timers dict (shared by every Timer). By default None: not recorded.

  • text (str, optional) – The message reported when the timer stops, formatted with the elapsed seconds. By default "Elapsed time: {:0.4f} seconds".

  • logger (Callable[[str], None] | None, optional) – The function that reports the message, by default print. None reports nothing.

See also

Timer.start

Start it by hand.

Timer.stop

Stop it by hand.

Examples

As a context manager:

>>> from lair.clock import Timer
>>> with Timer(text="took {:.0f} s"):
...     total = sum(range(1000))
took 0 s

By hand, without a report:

>>> timer = Timer(logger=None)
>>> timer.start()
>>> elapsed = timer.stop()
>>> elapsed >= 0
True

Methods

logger(*args[, sep, end, file, flush])

Prints the values to a stream, or to sys.stdout by default.

reset_timers()

Reset class timers

start()

Start a new timer

stop()

Stop the timer, and report the elapsed time