Back to results for “Profiling”
Python › Debugging & Profiling

How do you use the timeit module to accurately measure a small code snippet's execution time?

Intermediate

Answer

timeit.timeit(stmt, number=N) runs the given code snippet N times (default 1,000,000) and returns the TOTAL time taken, automatically minimizing common measurement pitfalls (like garbage collection interference) that a naive time.time() before/after comparison wouldn't account for.
import timeit

time_taken = timeit.timeit("'-'.join(str(n) for n in range(100))", number=10000)
print(f"Total: {time_taken:.4f}s")

# Comparing two approaches
print(timeit.timeit('"a" + "b"', number=1_000_000))
print(timeit.timeit('"".join(["a", "b"])', number=1_000_000))
Real-world example Comparing the actual performance of two different implementations of a small, frequently-called function.

Common follow-ups: Why does timeit disable automatic garbage collection during its measurement by default?