How to Compare Two Implementations with timeit in Python
Measure and compare the execution time of iterative vs recursive factorial functions using the timeit module.
Python code
30 linesimport timeit
def factorial_iterative(n):
result = 1
for i in range(2, n + 1):
result *= i
return result
def factorial_recursive(n):
if n == 0:
return 1
return n * factorial_recursive(n - 1)
if __name__ == "__main__":
n = 10
iterations = 10000
iterative_time = timeit.timeit(
lambda: factorial_iterative(n),
number=iterations
)
recursive_time = timeit.timeit(
lambda: factorial_recursive(n),
number=iterations
)
print(f"Iterative factorial({n}): avg {iterative_time / iterations:.8f} sec")
print(f"Recursive factorial({n}): avg {recursive_time / iterations:.8f} sec")
print(f"Recursive is {recursive_time / iterative_time:.2f}x slower")
Output
Iterative factorial(10): avg 0.00000054 sec
Recursive factorial(10): avg 0.00000105 sec
Recursive is 1.94x slower
How it works
timeit.timeit runs a callable a given number of times and returns total seconds. Dividing by the iteration count gives the average per call. The iterative function avoids function call overhead and stack frames, so it tends to be faster. The recursive version creates a new frame each call, adding overhead. Using lambda keeps the function call inside the timed block without extra setup.
Common mistakes
- Timing a function call without using `lambda` or `partial`, causing it to run before timing starts.
- Not specifying `number` leads to auto-calibration, giving inconsistent results.
- Including setup code inside the timed block, distorting the measurement.
Variations
- Use `timeit.repeat` to run multiple timing rounds and take the minimum for more stable results.
- Use the command-line interface: `python -m timeit -s 'from module import factorial_iterative' 'factorial_iterative(10)'`.
Real-world use cases
- Choosing between recursive and iterative implementations for a performance-critical algorithm.
- Benchmarking alternative data processing routines before deploying to production.
- Validating that a recent optimization actually improves latency in a hot code path.
Sponsored
More from Functions & basics
- Add Type Hints to Function Parameters and Return in Python easy
- Benchmark list append vs comprehension in Python easy
- Build a Context Manager in Python with contextlib.contextmanager easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
Keep learning
Related tutorials and quizzes for this topic.