Time a block of code with a context manager
Measure elapsed wall-clock time of a with-block using time.perf_counter.
- Python
- GreenSnippets
- MIT
- Executed with Python 3.11
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 exceptionsExample / expected 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.
Related snippets
- PHP Tested
Read a large CSV file with a generator
Stream CSV rows as associative arrays using fgetcsv, without loading the whole file into memory.
- JavaScript Tested
Run async tasks with a concurrency limit
Process a large list with at most N promises in flight at once, preserving result order.
- Bash
Run commands in parallel with xargs
Process many files concurrently with xargs -P, safely handling spaces and newlines in names.
- JavaScript Tested
Memoize a function
Cache results by argument so expensive pure functions only run once per distinct input.

