Timing
cl_forge.utils.Timing
dataclass
¶
A high-resolution timer that can be used as a context manager, decorator or manually.
Attributes:
| Name | Type | Description |
|---|---|---|
nanoseconds |
float
|
The elapsed time in nanoseconds. |
microseconds |
float
|
The elapsed time in microseconds. |
milliseconds |
float
|
The elapsed time in milliseconds. |
seconds |
float
|
The elapsed time in seconds. |
minutes |
float
|
The elapsed time in minutes. |
hours |
float
|
The elapsed time in hours. |
elapsed |
str
|
The elapsed time as a formatted string in seconds. |
is_running |
bool
|
Whether the timer is currently running. |
Examples:
As a context manager:
As a decorator:
@Timing # Works both with and without parenthesis
def my_function():
# code to time
my_function()
# prints 'Function 'my_function' took 0.123456s'
Direct call:
def my_function(x):
# code to time
timer = Timing(my_function)
result = timer(10)
# prints 'Function 'my_function' took 0.123456s'
# timer attributes are still available: timer.seconds
Manually:
timer = Timing()
timer.start()
# code to time
timer.stop()
print(timer.seconds)
# prints elapsed time in seconds
Note
- When used as a decorator, Timing prints the elapsed time to standard output.
- When used as a context manager or manually, the elapsed time can be accessed via the properties.
- The timer uses time.perf_counter_ns() for high-resolution timing.
- The timer raises
RuntimeErrorif the elapsed time is accessed before stopping.