Timing Real Code
Timeit and perf_counter.
Big O tells you how code grows. But sometimes you want real numbers. Is this version faster than that one, on my machine, today? Python has two great tools for that.

- Big O: the shape
- Sometimes you need real numbers
- Two tools
perf_counter
Time dot perf counter is a precise clock. Read it before and after, and subtract. Here we time building a list of squares, two ways. A plain loop, and a list comprehension. Run it. The comprehension is usually a little faster, because Python runs it more efficiently.
import time
start = time.perf_counter()
squares = []
for i in range(1_000_000):
squares.append(i * i)
loop = time.perf_counter() - start
start = time.perf_counter()
squares = [i * i for i in range(1_000_000)]
comp = time.perf_counter() - start
print(f"loop: {loop:.3f} s")
print(f"comprehension: {comp:.3f} s")loop: 0.066 s comprehension: 0.030 s
Timing tips
Timings jump around, because your computer is busy with other things. So run the code many times, like timeit does, and compare the best results. Use big inputs, so tiny differences don't hide in the noise. And always check Big O first. A better algorithm beats any small speed trick.
| key | value |
|---|---|
| timeit | runs code many times |
| perf_counter | a precise clock |
| Big inputs | reveal real differences |
| Big O first | algorithms beat tricks |
Summary
Perf counter and timeit give real timings. Repeat, use big inputs, and fix the algorithm before the details. Next, a quick Big O quiz.
Key takeaways- time.perf_counter()
- timeit.timeit()
- Repeat and compare