You cannot guess how fast an algorithm is: you have to measure it. In this topic we learn to measure time properly in Python and to understand the limits of measurements.

Timing with perf_counter

time.perf_counter() is a precise monotonic clock: the difference of two calls is seconds. time.time() follows the system clock and may jump.

python
import time

start = time.perf_counter()
total = sum(range(1_000_000))
elapsed = time.perf_counter() - start

print(total)
print("elapsed is positive:", elapsed > 0)
text
499999500000
elapsed is positive: True

We do not print the actual seconds: they differ on every run.

One measurement is not enough

The OS switches to other processes, caches are cold, the CPU changes frequency. The same code may take 3 ms once and 6 ms another time. Rule: repeat the measurement and take the minimum.

Repeats and the minimum
Repeats and the minimum

timeit

timeit.timeit(stmt, number=N) runs a statement N times and returns the total time:

python
import timeit