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 wrapperWhat 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
CSV Column AnalyzerProfile every CSV column with inferred types, empty-cell counts, unique values, and numeric min and max ranges.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.