pyxx.dev.TimeIt¶
- class pyxx.dev.TimeIt(print_duration: bool = True, units: str = 's', message: str = 'Code duration: {time} {units}')¶
Bases:
objectA context manager for measuring the duration of a code block.
This context manager can be used in a “with” statement to measure the duration of code within the statement. The resulting duration will be printed to the console when the “with” statement completes.
Warning
Using this timer will add some overhead to the code block being measured. The measured duration outputted to the terminal will be slightly larger than the actual execution time of the code block.
Examples
Time a code block and print the duration to the terminal:
>>> from pyxx.dev import TimeIt >>> import time >>> with TimeIt(units='ms', message='Execution time: {time:.2f} {units}'): ... # Code block of which to measure the duration ... time.sleep(1) Execution time: 1000.10 ms
Time a code block and access the duration in Python code following the code block:
>>> from pyxx.dev import TimeIt >>> import time >>> timer = TimeIt(print_duration=False) >>> with timer: ... # Code block of which to measure the duration ... time.sleep(1) >>> print(timer.duration('ms')) 1000.1010101010101
Methods
__init__([print_duration, units, message])Creates a new context manager for measuring the duration of a code block
duration([units])Returns the last measured duration from the context manager
- __init__(print_duration: bool = True, units: str = 's', message: str = 'Code duration: {time} {units}') None¶
Creates a new context manager for measuring the duration of a code block
- Parameters:
print_duration (bool, optional) – Whether to print to the terminal the duration of the code block
units (str, optional) – Only applicable if
print_durationisTrue. Specifies the units in which the duration will be displayed to the terminal (default is's')message (str, optional) – Only applicable if
print_durationisTrue. The message template to display the duration (default is'Code duration: {time} {units}'). The{time}and{units}placeholders will be replaced by the duration and units, respectively
- duration(units: str = 's') float¶
Returns the last measured duration from the context manager
- Parameters:
units (str) – The units in which to return the duration (default is
's')