typestar

Timing context manager in Python

Context managers guarantee cleanup; this one measures elapsed time.

import time
from contextlib import contextmanager

@contextmanager
def timed(label):
    start = time.perf_counter()
    try:
        yield
    finally:
        elapsed = time.perf_counter() - start
        print(f"{label}: {elapsed:.3f}s")

How it works

  1. @contextmanager turns the generator into a with-block helper.
  2. Code before the yield runs on entry, recording the start time.
  3. The finally block always prints the elapsed time on exit.

Keywords and builtins used here

The run, in numbers

Lines
11
Characters to type
204
Tokens
50
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 29 seconds.

Type this snippet

Step 2 of 5 in Protocols & context managers, step 16 of 53 in Pythonic Python.

← Previous Next →