Context Manager Timer Decorator

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

PythonCli Tooling

Code

pythonsnippet
18 lines
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

What the code does

Context Manager Timer Decorator keeps everything in the functions timer, timed and wrapper.

Using it

The primary signature is def timer(label='operation')

timer is what another module would consume; nothing else here is load-bearing for callers.

Key statements

def timer(label='operation'):
    start = time.perf_counter()
    try:
        yield
    finally:
        elapsed = time.perf_counter() - start
        print(f'{label}: {elapsed:.4f}s')
def wrapper(*args, **kwargs):
    with timer(func.__name__):
        return func(*args, **kwargs)

Interactive Tools for This Topic

FAQ

What has to be installed first?
Nothing — the runtime itself provides everything the code touches. Every import resolves inside the standard library — `time`, `contextlib`. The file defines `timer`, `timed`, `wrapper` at load time.