Skip to content

Timing

cl_forge.utils.Timing dataclass

Timing(fn: Callable[..., Any] | None = None)

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:

with Timing() as timer:
    # code to time
print(timer.elapsed)
# prints 'Elapsed time: 0.123456s'

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 RuntimeError if the elapsed time is accessed before stopping.
Source code in src/cl_forge/core/timing.py
def __init__(self, fn: Callable[..., Any] | None = None, /) -> None:
    self._fn: Callable[..., Any] | None = fn
    self._start_ns: int | None = None
    self._end_ns: int | None = None

nanoseconds property

nanoseconds: float

The elapsed time in nanoseconds.

microseconds property

microseconds: float

The elapsed time in microseconds.

milliseconds property

milliseconds: float

The elapsed time in milliseconds.

seconds property

seconds: float

The elapsed time in seconds.

minutes property

minutes: float

The elapsed time in minutes.

hours property

hours: float

The elapsed time in hours.

elapsed property

elapsed: str

The elapsed time as a formatted string in seconds.

is_running property

is_running: bool

Whether the timer is currently running.

start

start() -> None

Start the timer.

Source code in src/cl_forge/core/timing.py
def start(self) -> None:
    """Start the timer."""
    self._start_ns = time.perf_counter_ns()
    self._end_ns = None

stop

stop() -> None

Stop the timer.

Source code in src/cl_forge/core/timing.py
def stop(self) -> None:
    """Stop the timer."""
    self._end_ns = time.perf_counter_ns()