Writing a timing context manager in Python

Backend Live Coding November 13, 2026 python

Write a context manager that measures execution time.

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
# ======================================================================
# Q: Write a context manager that measures execution time.
# ======================================================================

from contextlib import contextmanager

@contextmanager
def timer(label):
    start = time.perf_counter()
    try:
        yield
    finally:                          # runs even if an exception occurs
        logger.info('%s took %.1f ms', label, (time.perf_counter() - start) * 1000)

with timer('erp sync'):
    sync_stock()