AI Hints
Home›DSA in Python Tutorial›Space and Time
DSA in Python · Lesson 11 of 132

Timing Real Code

Timeit and perf_counter.

⏱ 2 min read▶ Video at 11:31🎓 Free
Watch this lesson in the DSA in Python courseWatch on YouTube ↗Full DSA in Python course

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.

Timing Real Code
From the video: Timing Real Code
  • 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.

timing.pypython
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")
Output
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.

keyvalue
timeitruns code many times
perf_countera precise clock
Big inputsreveal real differences
Big O firstalgorithms 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
Next up: Big O Quiz — test yourself