timing
timing
¶
Timing utilities for measuring and reporting experiment durations.
This module provides a simple Timer context manager for measuring execution time and formatting durations in a human-readable format.
Examples:
from alberta_framework.utils.timing import Timer
with Timer("Training"):
# run training code
pass
# Output: Training completed in 1.23s
# Or capture the duration:
with Timer("Experiment") as t:
# run experiment
pass
print(f"Took {t.duration:.2f} seconds")
Timer(name='Operation', verbose=True, print_fn=None)
¶
Context manager for timing code execution.
Measures wall-clock time for a block of code and optionally prints the duration when the block completes.
Attributes: name: Description of what is being timed duration: Elapsed time in seconds (available after context exits) start_time: Timestamp when timing started end_time: Timestamp when timing ended
Examples:
with Timer("Training loop"):
for i in range(1000):
pass
# Output: Training loop completed in 0.01s
# Silent timing (no print):
with Timer("Silent", verbose=False) as t:
time.sleep(0.1)
print(f"Elapsed: {t.duration:.2f}s")
# Output: Elapsed: 0.10s
# Custom print function:
with Timer("Custom", print_fn=lambda msg: print(f">> {msg}")):
pass
# Output: >> Custom completed in 0.00s
Args: name: Description of the operation being timed verbose: Whether to print the duration when done print_fn: Custom print function (defaults to built-in print)
Source code in src/alberta_framework/utils/timing.py
elapsed()
¶
Get elapsed time since timer started (can be called during execution).
Returns: Elapsed time in seconds
format_duration(seconds)
¶
Format a duration in seconds as a human-readable string.
Args: seconds: Duration in seconds
Returns: Formatted string like "1.23s", "2m 30.5s", or "1h 5m 30s"
Examples:
format_duration(0.5) # Returns: '0.50s'
format_duration(90.5) # Returns: '1m 30.50s'
format_duration(3665) # Returns: '1h 1m 5.00s'