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
Choosing number and repeat
number controls how many times the statement runs inside one measurement. If it is too small, each measurement is so short that clock resolution and overhead dominate. If it is too large, the benchmark takes needlessly long.
A good rule is to aim for each measurement to last at least 0.2 seconds. timeit.Timer.autorange does this for you: it increases number until the total time reaches that threshold.
repeat controls how many measurements are taken; five to seven is usually enough to see the minimum and the spread.
Worked Example: Letting autorange Choose
We let autorange pick a loop count for a fast and a slow statement.
import timeit
fast = timeit.Timer("x = 42 + 99")
slow = timeit.Timer("sum(range(200_000))")
for name, timer in [("fast", fast), ("slow", slow)]:
number, total = timer.autorange()
best = min(timer.repeat(repeat=5, number=number)) / number
print(f"{name}: number={number}, total={total:.2f}s, best {best * 1e9:.1f} ns per loop")
The fast statement needs millions of loops to fill 0.2 seconds, while the slow one needs only a few dozen. autorange gives each statement a sensible number automatically, so the per-loop results are trustworthy.
Practical Tips
If you choose number by hand, start with a small value, look at the total time, and scale it up until each measurement takes a fraction of a second. For code that changes state, such as appending to a list, remember that every loop sees the state left by the previous one, so prepare fresh data in the statement or keep number low.
Keep the chosen values in your notes, so later runs use the same settings.
Common Mistakes
- Using number=1 for very fast statements.
- Using a huge number for slow code.
- Forgetting to divide by the chosen number.
- Taking too few repeats to judge noise.
Quick Summary
- number sets executions per measurement.
- Aim for at least 0.2 s per measurement.
- autorange picks number automatically.
- Use 5 to 7 repeats and keep the minimum.
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