opentau.utils.benchmark

Utilities for benchmarking and timing code execution.

This module provides the TimeBenchmark class for measuring execution time using context managers or decorators in a thread-safe manner.

Classes

TimeBenchmark([print])

Measures execution time using a context manager or decorator.

class opentau.utils.benchmark.TimeBenchmark(print=False)[source]

Bases: ContextDecorator

Measures execution time using a context manager or decorator.

This class supports both context manager and decorator usage, and is thread-safe for multithreaded environments.

Parameters:

print – If True, prints the elapsed time upon exiting the context or completing the function. Defaults to False.

Examples

Using as a context manager:

>>> benchmark = TimeBenchmark()
>>> with benchmark:
...     time.sleep(1)
>>> print(f"Block took {benchmark.result:.4f} seconds")
Block took approximately 1.0000 seconds

Using with multithreading:

import threading

benchmark = TimeBenchmark()

def context_manager_example():
    with benchmark:
        time.sleep(0.01)
    print(f"Block took {benchmark.result_ms:.2f} milliseconds")

threads = []
for _ in range(3):
    t1 = threading.Thread(target=context_manager_example)
    threads.append(t1)

for t in threads:
    t.start()

for t in threads:
    t.join()

# Expected output:
# Block took approximately 10.00 milliseconds
# Block took approximately 10.00 milliseconds
# Block took approximately 10.00 milliseconds
__init__(print=False)[source]
property result
property result_ms