Specifying number of loops in timeit – Python 2026 with Efficient Code

Efficient Code Mar 15, 2026

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 number when 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,000Reach ~0.5–2 seconds total
Medium (microseconds)1,000 – 10,000Stable measurement
Slower (milliseconds)100 – 1,000Avoid 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 number when comparing two different implementations
  • Start with 1000–5000 and adjust based on runtime
  • Combine with repeat=7 and take the minimum time
  • Never rely on default number=1_000_000 for 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

Related Tutorials

Share:
Last updated: March 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices