timeit & Microbenchmarks
Microbenchmarks measure small code snippets precisely. The timeit module eliminates common timing pitfalls (garbage collection, setup overhead) for fair comparisons.
Search across all documentation pages
Microbenchmarks measure small code snippets precisely. The timeit module eliminates common timing pitfalls (garbage collection, setup overhead) for fair comparisons.
import timeit
time_a = timeit.timeit("[x*x for x in range(1000)]", number=10000)
time_b = timeit.timeit("list(map(lambda x: x*x, range(1000)))", number=10000)
print(f"comprehension: {time_a:.4f}s, map: {time_b:.4f}s")When to reach for this:
import timeit
setup = """
from pathlib import Path
data = list(range(10000))
"""
stmt_list = "[x * 2 for x in data]"
stmt_gen = "list(x * 2 for x in data)"
t_list = timeit.timeit(stmt_list, setup=setup, number=1000)
t_gen = timeit.timeit(stmt_gen, setup=setup, number=1000)
print(f"list comp: {t_list:.4f}s, gen: {t_gen:.4f}s, ratio: {t_gen/t_list:.2f}x")# Command line
# python -m timeit "[x*x for x in range(1000)]"
# python -m timeit -s "import math" "math.sqrt(2)"What this demonstrates:
setup runs once; stmt runs number timespython -m timeit for quick one-linersnumber until total time is > 0.2s| Pitfall | Fix |
|---|---|
| GC during timing | timeit disables GC by default |
| Cold cache | Warm up before timing |
| Debug mode | Benchmark without -O unless measuring production |
Tiny number | Increase until timer resolution is negligible |
-O or production config differs. Fix: benchmark the deployment configuration.| Alternative | Use When | Don't Use When |
|---|---|---|
| pytest-benchmark | Regression tracking in CI | Quick one-off comparison |
| cProfile | Finding what to benchmark | Comparing two implementations |
| pyperf | Rigorous statistical benchmarks | Quick checks |
timeit for isolated snippets. perf_counter for full function timing.
Increase until total elapsed is 0.2-2 seconds. timeit auto-calibrates with autorange.
Use asyncio.run() in setup/stmt or dedicated async benchmark tools.
Use setup to define data; reference it in stmt string.
Each call is independent. For threaded code, benchmark the full concurrent scenario separately.
python -m timeit "sum(range(1000))" runs with auto-calibrated repetitions.
timeit disables GC during timing by default.
Convenient for exploration. Use module timeit for reproducible scripts.
Commit a benchmark script with fixed number and document hardware/OS.
When the snippet is not the application hotspot. Profile first.
Stack versions: This page was written for Python 3.14.0, FastAPI 0.115+, Django 5.2, Flask 3.1, Pydantic 2, PyTorch 2.6+, pandas 2.2+, Polars 1.x, ruff 0.9+, and uv 0.6+.
Reviewed by Chris St. John·Last updated Jul 19, 2026