Lesson · Performance & Profiling
Timing & Benchmarking
75 min readTiming & Benchmarking
Benchmarking measures elapsed time under controlled conditions. `perf_counter` and `timeit` help, but warm-up, setup cost, noise, and unrealistic microbenchmarks can invalidate conclusions.
Learning goals
- Measure an elapsed interval by subtracting two
time.perf_counter()readings taken around the code under test. - Use
timeitto execute a small snippet many times and turn its total into an average per run. - Name the conditions a benchmark must control, including setup outside the timed block and warm-up inside it.
- Explain why a microbenchmark can rank two alternatives differently from the application it was meant to model.
- Choose between a single timed run, a repeated
timeitmeasurement, and a full workload measurement for a given question.
Mental model
The ladder narrows and stabilizes the measurement as you move down: a single interval tells you what one run did, a timeit measurement averages many repeats of a small fixed snippet, and neither proves anything about the application until the snippet is checked against representative input. Warm-up belongs in that check, because the first execution of anything pays import, allocation, and cache costs that later executions do not.
Mental model
read it top to bottom
question about speed ↓ a single interval from real code? perf_counter around the block (one sample, includes warm-up) ↓ a stable number for a tiny snippet? timeit(stmt, number=...) (many runs, reduced noise) ↓ does the number answer the real question? compare the snippet against a representative workload
Core idea
A benchmark is an experiment: it compares something under conditions you control, and the number is only as good as those conditions. perf_counter provides a precise elapsed interval for real code, timeit provides a stable average for tiny repeated snippets, and either can mislead when setup, warm-up, or noise dominates the measured block. State the question first, keep setup out of the timed region, repeat the measurement, and treat the result as evidence about the snippet measured, not about the whole program.
time.perf_counter
time.perf_counter() is a high-resolution monotonic clock suitable for measuring elapsed duration. Subtract two readings rather than interpreting the absolute number.
timeit
timeit repeatedly executes small snippets while reducing common timing mistakes. It is useful for microbenchmarks but cannot tell you whether the benchmark represents real application behavior.
Warm-up considerations
An editor should make the active interpreter visible and provide syntax, linting, debugging, and terminal access without hiding how Python itself runs. Keep environment selection explicit.
Microbenchmark traps
A microbenchmark isolates a tiny operation and can overemphasize costs that are irrelevant in a full application. Validate any conclusion against representative end-to-end work.
Responsible comparisons
A responsible comparison changes one thing at a time, runs every candidate under the same conditions, and reports a spread from repeated runs rather than a single number. It also checks that the snippets do equal work: a benchmark that includes setup against one that does not will show a difference that belongs to the benchmark, not to the code.
Walkthrough
- The first
perf_counter()call records a starting reading,sum(range(1_000_000))runs and its result is discarded, and the second call minus the first giveselapsed; the absolute readings mean nothing on their own, only the difference is a duration. - The measured block includes everything between the two calls, so the million-element
range, the summation, and the temporary objects it creates all land inelapsed, which is what makes this a measurement of the whole expression. timeit("sum(range(1000))", number=10_000)runs the snippet ten thousand times and returns the total seconds for all runs; dividing bynumbergives the average per run, which is the number to compare between candidates.- Predict before running: which print reports the larger raw number, and why the two prints are not directly comparable even though both time a sum over a range.
Experiments to try
- Wrap the
timeitcall inmin(timeit.repeat(..., number=1000, repeat=5))and compare the minimum with one plain run; explain why the minimum is the usual summary for a repeated benchmark. - Time the first call and the hundredth call of a function that builds a small list; describe how warm-up (imports, first allocations, cache state) shows up in the first number.
- Put a
printinside the timed snippet and compare the measurement with the print-free version; explain why the I/O makes the comparison useless for judging the computation. - Measure the same loop with
perf_counterinside a script and withtimeit; list one condition each method controls differently (setup, repetition, output).
Common mistakes
- Trusting a single run of something short: one sample folds in scheduler noise and warm-up, so the number can move by a large factor between attempts.
- Leaving setup inside the timed block: imports, file reads, and container construction land in the measurement and hide the cost of the operation you meant to compare.
- Comparing a snippet with the application it stands for: a loop over 1,000 items can rank two candidates opposite to the real workload, because per-operation overheads and growth trade places as size changes.
- Treating a
perf_counterreading as an absolute time: the reference point is undefined, so only differences between two readings in the same process are meaningful.
Practice: Easy
- Time
sum(range(1_000)),sum(range(100_000)), andsum(range(10_000_000))withperf_counterand record the three intervals; check whether their ratios match the ratios of the input sizes. - Run the worked example five times as a script and write down the five
elapsedvalues; describe how much they vary and what that says about single-sample timing. - Run
timeit("sum(range(1000))", number=n)fornof 1, 100, and 10_000; divide each result bynand note how the per-run value stabilizes asngrows.
Practice: Medium
- Write
bench(label, fn)that times a callable withtimeitand prints the average seconds per call; use it to comparesum([n * n for n in range(1000)])withsum(n * n for n in range(1000)), then explain the winner with the allocation the list version performs. - Move the timed expression in the worked example into a function and call it ten times with
perf_counter; compare the first call with the average of the last nine and name what changed. - Write a benchmark for slicing a 100,000-element list, first with the list construction left inside the timed statement, then with it moved into setup; report both numbers and what the difference was actually measuring.
Practice: Hard
- Build a harness
bench(fn, number, repeat)that reports the minimum, median, and spread acrossrepeatruns; use it on the list-versus-generator sum from Medium 1 and write a conclusion that separates a real difference from noise. - Produce three invalid measurements on purpose: one dominated by warm-up, one with setup inside the timed block, and one whose snippet is too short for the clock to resolve. Explain the mechanism behind each bad number.
- Take a small script with a
main()that mixes I/O and computation, benchmark it end to end, and explain why the total time cannot tell you which part to change and what additional evidence a profile would provide.
Lesson checklist
- I can measure an elapsed interval by subtracting two
perf_counterreadings and say why the absolute values are not comparable. - I can produce a
timeitmeasurement and convert its total into an average per run. - I can name the conditions a benchmark controls: setup outside the timed block, warm-up accounted for, repeated runs, representative size.
- I can give one reason a microbenchmark result might not hold for the application it came from.
Remember
Timing is an experiment: decide the question, keep setup out of the measured block, repeat the measurement, and treat one reading as a sample rather than a fact. `perf_counter` measures the elapsed interval between two points in real code, while `timeit` repeats a small snippet and reports the total for those runs, which you divide by `number` for an average. A benchmark transfers to the application only when its workload, size, and conditions resemble the real thing.
Interview angles
What is the main purpose of **time.perf_counter**?+
time.perf_counter() is a high-resolution monotonic clock suitable for measuring elapsed duration. Subtract two readings rather than interpreting the absolute number.
What should you pay attention to when using **timeit**?+
timeit repeatedly executes small snippets while reducing common timing mistakes. It is useful for microbenchmarks but cannot tell you whether the benchmark represents real application behavior.
How does **Warm-up considerations** fit into this lesson?+
An editor should make the active interpreter visible and provide syntax, linting, debugging, and terminal access without hiding how Python itself runs. Keep environment selection explicit.
Why is one timed run of a short operation unreliable, and what does `timeit` do about it?+
A single sample includes scheduler noise and warm-up costs, such as imports, first allocations, and cache state, so short runs vary widely between attempts. timeit executes the snippet number times and returns the total, which averages the noise across runs; repeating the whole measurement and taking the minimum is a further safeguard.