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.

Easy Python 3.9+ Aug 9, 2026 Functions & basics 14 views 0 copies

Python code

30 lines
Python 3.9+
import 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

stdout
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

  1. Use `timeit.repeat` to run multiple timing rounds and take the minimum for more stable results.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Functions & basics

Related tutorials and quizzes for this topic.