timeit and microbenchmarks
coreintermediatetimeit.timeit(stmt, setup, number=N) runs a snippet N times and returns the total time, averaging out noise. It is the right tool for comparing two small alternatives — never for timing a whole application, where cProfile is better.
Think of it as
A single time.perf_counter() measurement is one photograph — it can be blurry from a random system hiccup. timeit is averaging many photographs together, which is why it is trusted for comparing two small snippets where the difference might be tiny.
What we're doing: Compare two ways of building a list of squares and measure which one timeit actually reports as faster.
- 3
- A list comprehension, run 10,000 times — timeit sums the total time across all runs.
- 4
- The same job via map() and a lambda, timed the same way for a fair comparison.
list comprehension: 0.5250s
map + lambda: 0.9488sWhy this works: Both produce the identical list of squares — timeit's repeated runs (10,000 here) average out any single-run noise, making the real, consistent difference between the two approaches visible rather than lost in measurement jitter.
Trusting a single time.perf_counter() measurement over timeit
Wrong
Better
What you see: Two runs of the same benchmark give noticeably different results, making it impossible to trust a conclusion drawn from either one.
Why: A single measurement can be skewed by a background process, a garbage collection pause, or CPU frequency scaling — timeit's repeated-run averaging (and disabling the GC by default) is specifically designed to cancel out exactly this kind of one-off noise.
- setup runs ONCE — s = set(range(1000)); x = 999 — before timing starts
- stmt runs number= times — x in s — timed on every single iteration
- Total time returned — summed across all runs — divide by number for per-run average
- Noise averages out — a single perf_counter() call can be skewed by one GC pause; 10,000 runs is not
timeit — the interfaces worth knowing
Together
Remember: timeit.timeit(stmt, setup, number=N) runs a snippet N times, averaging out noise — for small alternatives only.
See also: cprofile and pstats · choosing data structures

