Context Manager Timer Decorator

Measure function execution time with a context manager and decorator for performance profiling.

PythonCli Tooling

Code

snippet
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 wrapper