Context Manager for Timing Blocks
Wrap a code block in a context manager that measures elapsed time, so timing instrumentation is added without clutter or manual bookkeeping.
Code
import time
from contextlib import contextmanager
@contextmanager
def timer(label: str):
start = time.perf_counter()
try:
yield
finally:
elapsed_ms = (time.perf_counter() - start) * 1000
print(f"{label}: {elapsed_ms:.2f}ms")
with timer("query"):
total = sum(i * i for i in range(10000))Output
Captured from a sandboxed run of this snippet in the build pipeline.
query: 0.88msHow the snippet works
Context Manager for Timing Blocks keeps everything in the function timer.
Applying it
The main signature reads def timer(label: str)
Import timer from the file and call it — the rest of the code is implementation detail.
Statements that matter
def timer(label: str):
start = time.perf_counter()
try:
yield
finally:
elapsed_ms = (time.perf_counter() - start) * 1000
print(f"{label}: {elapsed_ms:.2f}ms")
with timer("query"):
total = sum(i * i for i in range(10000))
Interactive Tools for This Topic
FAQ
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement. Every import resolves inside the standard library — `time`, `contextlib`. The file defines `timer` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.