Context Manager Timer Decorator
Measure function execution time with a context manager and decorator for performance profiling.
Code
import time, functools
from contextlib import contextmanager
@contextmanager
def timer(label='operation'):
start = time.perf_counter()
try:
yield
finally:
elapsed = time.perf_counter() - start
print(f'{label}: {elapsed:.4f}s')
def timed(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
with timer(func.__name__):
return func(*args, **kwargs)
return wrapperReport a problem with this exampleOpens a pre-filled issue on GitHub.