Design Repeatable Performance Measurements
Core idea
Define a workload, correctness criterion and metric before measuring. Use perf_counter for elapsed time and process_time for CPU time consumed by the current process. Record interpreter version, input distribution and environment; separate setup from work where appropriate. Repeat and report variability rather than a single universal speed claim.
from time import perf_countervalues = tuple(range(100))start = perf_counter()answer = sum(values)elapsed = perf_counter() - startprint(answer, elapsed >= 0)The result checks correctness and the clock measures elapsed seconds. No specific duration is promised.
Expected output:
4950 TrueRepeat and retain samples
from time import perf_counter_nsfrom statistics import mediansamples = []for _ in range(5): start = perf_counter_ns() result = sum(range(1000)) samples.append(perf_counter_ns() - start) assert result == 499500print(len(samples), median(samples) >= 0)Five samples support a summary while retaining individual variation.
Expected output:
5 TrueCommon mistake
Do not compare different workloads, include unrelated setup in only one candidate, or mistake a microbenchmark for production latency.
Practice
Measure sum on two fixed input sizes with five repeats each. Record Python version, hardware, input size, samples and correctness; do not infer scaling from one size.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Measurement methodology
Check your understanding of measurement methodology.
What is printed?
from time import perf_countera=perf_counter(); b=perf_counter()print(b>=a)What is printed?
from statistics import medianprint(median([8,2,5]))What must two candidate benchmarks share?
What does process_time exclude?