Using timeit in Python 2026 with Efficient Code
The timeit module is Python’s built-in tool for accurately measuring the execution time of small code snippets. In 2026, with faster interpreters and free-threading, using timeit properly is essential for reliable benchmarking and performance optimization.
This March 15, 2026 guide shows modern best practices for using timeit effectively in your daily development workflow.
TL;DR — Key Takeaways 2026
timeitautomatically runs your code multiple times and calculates the best time- It disables garbage collection during timing for more accurate results
- Use
timeit.timeit()for simple cases andTimerclass for advanced control - Always compare before vs after when optimizing
- Combine with
time.perf_counter()for larger functions
1. Basic Usage of timeit
import timeit
# Simple one-liner
time_taken = timeit.timeit('sum(range(10000))', number=1000)
print(f"sum(range(10000)) took {time_taken:.6f} seconds")
# With setup code
setup = "from math import sqrt"
stmt = "sqrt(123456789)"
result = timeit.timeit(stmt, setup=setup, number=100000)
print(f"sqrt took {result:.6f} seconds")
2. Modern timeit Patterns in 2026
import timeit
import numpy as np
def slow_version():
return [x**2 for x in range(10000)]
def fast_version():
return np.arange(10000)**2
# Compare two approaches fairly
print("List comprehension:", timeit.timeit(slow_version, number=100))
print("NumPy vectorized: ", timeit.timeit(fast_version, number=100))
# Using Timer class for more control
timer = timeit.Timer(
stmt="np.sum(arr**2)",
setup="import numpy as np; arr = np.arange(100000)"
)
print("Best time:", timer.timeit(number=50))
3. Best Practices for Using timeit in 2026
- Use
number=to control how many times the code runs - Use
repeat=+min()for more reliable results - Always include setup code to avoid measuring import time
- Time realistic workloads, not tiny toy examples
- Disable garbage collection during timing with
gc.disable()for maximum accuracy - Compare relative improvement, not absolute times
4. Recommended timeit Pattern (2026)
def benchmark(stmt, setup="", number=1000, repeat=5):
"""Reliable benchmarking helper"""
timer = timeit.Timer(stmt=stmt, setup=setup)
times = timer.repeat(repeat=repeat, number=number)
best = min(times) / number
print(f"Best time per loop: {best:.8f} seconds")
return best
# Usage
benchmark(
stmt="np.sum(arr**2)",
setup="import numpy as np; arr = np.arange(100000)",
number=100
)
Conclusion — Using timeit in Python 2026
timeit is the most reliable way to measure small pieces of Python code accurately. In 2026, with increasingly complex applications and free-threading, regularly using timeit helps you make data-driven optimization decisions instead of relying on guesswork. Make it part of your development workflow — time before you optimize.
Next steps:
- Add
timeitbenchmarks to your critical functions - Related articles: Why Should We Time Our Code 2026 • Efficient Python Code 2026