timeit runs a statement repeatedly and limits common interference, including garbage collection during timing. It answers focused questions; it does not model an entire application's performance by itself.
Practical example
from timeit import repeat
samples = [str(number) for number in range(100)]
times = repeat(
"','.join(samples)",
globals={"samples": samples},
number=10_000,
repeat=5,
)
print(f"best: {min(times):.4f}s")
Build a fair comparison
Setup should prepare data without entering the measured statement. Give alternatives the same input, iteration count, and lightly loaded environment. The minimum among repeats is the best observed case, not a production guarantee.
Use the command line
python -m timeit "sum(range(100))" is enough for a quick check. Record the command, Python version, and machine when publishing a result.
Avoid premature optimization
A tiny improvement in a rare operation does not justify opaque code. Find the bottleneck in the real workflow first, then use a microbenchmark to test one specific hypothesis.
Keep learning
Strengthen the foundation with Python guide for beginners. The official Python documentation, accessed July 22, 2026, documents the API, limitations, and version differences.