Skip to content
GreenSnippets

Time a block of code with a context manager

Measure elapsed wall-clock time of a with-block using time.perf_counter.

Python
import time


class Timer:
    def __enter__(self):
        self._start = time.perf_counter()
        self.elapsed = None
        return self

    def __exit__(self, exc_type, exc, tb):
        self.elapsed = time.perf_counter() - self._start
        return False  # never swallow exceptions

Example / expected output

Output
with Timer() as t:
    sum(range(1_000_000))
print(f"{t.elapsed:.3f}s")

How it works

time.perf_counter() is the right clock for measuring durations: it is monotonic and high resolution. The result is stored on the object so it can be logged or asserted after the block, even if the block raised.