Compare Small Workloads with timeit
Core idea
timeit.Timer runs a statement or callable repeatedly, excluding its setup from the timed interval. repeat returns total durations for repeated groups; divide each by number for per-call time. Default garbage collection is temporarily disabled, which matters for allocation-heavy code. Compare equivalent results and treat best or median samples as local observations.
import timeitxs = tuple(range(50))def a(): return sum(xs)def b(): total = 0 for x in xs: total += x return totalassert a() == b()t1 = timeit.Timer(a).repeat(repeat=3, number=100)t2 = timeit.Timer(b).repeat(repeat=3, number=100)print(a(), len(t1), len(t2))Each candidate executes the same calculation; durations are not asserted.
Expected output:
1225 3 3Observe setup and repeat semantics
from timeit import Timercalls = []timer = Timer(lambda: calls.append('work'), setup=lambda: calls.append('setup'))samples = timer.repeat(repeat=2, number=3)print(calls.count('setup'), calls.count('work'))print(len(samples))Setup runs once per timed group, and the statement runs number times within it.
Expected output:
2 62Common mistake
Avoid measuring a consumed iterator or mutating a shared input across repeats unless that is the intended workload. Benchmark setup must restore necessary state; do not use the growing list demonstration as a fair speed comparison.
Practice
Use timeit to compare two equivalent ways of calculating squares for a fixed tuple; retain all per-call samples and record the GC policy.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Timeit
Check your understanding of timeit.
What is printed?
from timeit import Timerprint(len(Timer(lambda: 1).repeat(repeat=4,number=2)))What is printed?
from timeit import Timerx=[]Timer(lambda:x.append(1)).timeit(number=3)print(len(x))How do you obtain seconds per call from a group?
Why reset mutable benchmark state?