Specifying number of loops in timeit – Python 2026 with Efficient Code
The number parameter in timeit controls how many times your code snippet runs during each measurement. Choosing the right value is crucial for getting accurate and meaningful benchmark results in 2026.
This March 15, 2026 guide explains how to properly set the number of loops and why it matters for efficient code optimization.
TL;DR — Key Takeaways 2026
number= how many times the statement runs in one timing- Too small → noisy and inaccurate results
- Too large → includes system noise and takes too long
- Best practice: Aim for total runtime between 0.2 and 2 seconds per repeat
- Always use the same
numberwhen comparing two versions
1. Basic Usage of number Parameter
import timeit
# Default (number=1000000) - often too many for slow code
timeit.timeit('sum(range(1000))')
# Recommended: Control the number of loops
result = timeit.timeit(
stmt='sum(range(10000))',
number=5000 # Run the code 5000 times per measurement
)
print(f"Best of 5: {result:.6f} seconds for 5000 loops")
2. Modern Best Practice Pattern (2026)
import timeit
def benchmark(stmt, setup="", number=1000, repeat=7):
"""Reliable benchmarking with smart loop count"""
timer = timeit.Timer(stmt=stmt, setup=setup)
times = timer.repeat(repeat=repeat, number=number)
best_per_loop = min(times) / number
print(f"{stmt[:50]:50} → {best_per_loop*1_000_000:8.2f} µs per loop "
f"({number:,} loops)")
return best_per_loop
# Usage examples
benchmark("sum(range(100000))")
benchmark("[x**2 for x in range(10000)]")
benchmark("np.sum(np.arange(100000)**2)",
setup="import numpy as np")
3. How to Choose the Right number of loops
| Code Speed | Recommended number | Goal |
|---|---|---|
| Very fast (nanoseconds) | 100,000 – 1,000,000 | Reach ~0.5–2 seconds total |
| Medium (microseconds) | 1,000 – 10,000 | Stable measurement |
| Slower (milliseconds) | 100 – 1,000 | Avoid long wait times |
4. Best Practices for number of loops in 2026
- Target 0.2 – 2 seconds total runtime per repeat for best accuracy
- Use the same
numberwhen comparing two different implementations - Start with 1000–5000 and adjust based on runtime
- Combine with
repeat=7and take the minimum time - Never rely on default
number=1_000_000for real benchmarks
Conclusion — Specifying number of loops in timeit (2026)
Choosing the correct number of loops is a key part of reliable benchmarking. In 2026, developers who properly control timeit parameters get trustworthy performance data, make better optimization decisions, and write significantly more efficient code.
Next steps:
- Use the
benchmark()helper above in all your performance tests - Related articles: Using timeit in Python 2026 • Efficient Python Code 2026