Objective
"Version B is 5% faster" is a statistical claim. By the end of this lesson you should be able to write a timing harness that avoids the common traps, explain the numbers it prints, and say whether a measured difference is real.
Why one timing is meaningless
A single run of a function is affected by:
- Cold state. The first call takes page faults, instruction and data cache misses, untrained branch predictors, lazy initialisation and (in JIT languages) compilation.
- Frequency scaling and turbo. The CPU clock changes with load and temperature; on laptops with performance and efficiency cores the scheduler may move you between them.
- Interference. Other processes, interrupts, and the OS scheduler preempting you.
- Layout effects. Code alignment and memory addresses change between builds and runs, which alone can shift timings by several percent.
So a benchmark must warm up, repeat many times, and summarise the distribution. On a dedicated benchmark machine you would also pin the process to a core (taskset on Linux), fix the CPU frequency governor, and disable turbo.
Which statistic to report
Timing noise is one-sided: interference only ever makes runs slower. Hence:
- The minimum estimates the cost with no interference; good for comparing tight code paths.
- The median is robust to occasional large outliers and reflects typical behaviour.
- The mean is dragged by outliers; report it only with the spread, and only if outliers are part of what you care about.
- Always show the spread (max, interquartile range or standard deviation). A difference smaller than the run-to-run spread needs a statistical test, not eyeballing.
Dead-code elimination and constant folding
An optimising compiler removes computations whose results are unused, and evaluates at compile time anything it can. A benchmark that discards its result often times an empty loop. The fix is to make the result observable without adding cost: Google Benchmark's benchmark::DoNotOptimize(x) and benchmark::ClobberMemory() are thin inline-assembly barriers that tell the compiler "this value is used" and "memory may have changed". Also make inputs opaque (read them from data generated at run time) so the computation cannot be folded.
Google Benchmark in one paragraph
The library runs each benchmark function in a loop (for (auto _ : state)), picks the iteration count automatically until the timing is stable, supports parameter sweeps (->Range(8, 8 << 10)), repetitions with mean, median and standard deviation (--benchmark_repetitions=20), and reports CPU time as well as wall time. It solves the harness problems for you; the measurement-design problems (realistic data, warm versus cold caches, what to compare) remain yours.
Worked example
a minimal timing harness
Write a small harness that warms up, repeats, and reports min, median and max. Use it to time summing a million doubles stored in a std::vector and in a std::list, and show what happens if the result is discarded.
Show solutionHide solution
#include <algorithm>
#include <chrono>
#include <cstdio>
#include <list>
#include <numeric>
#include <random>
#include <vector>
// Force the compiler to treat a value as used (same idea as benchmark::DoNotOptimize).
template <class T>
inline void do_not_optimize(T const& value) {
asm volatile("" : : "r,m"(value) : "memory");
}
template <class F>
void bench(const char* name, F&& f, int warmup = 3, int reps = 21) {
using clock = std::chrono::steady_clock;
for (int i = 0; i < warmup; ++i) f(); // warm caches, branch predictors, page faults
std::vector<double> us;
for (int i = 0; i < reps; ++i) {
auto t0 = clock::now();
f();
auto t1 = clock::now();
us.push_back(std::chrono::duration<double, std::micro>(t1 - t0).count());
}
std::sort(us.begin(), us.end());
std::printf("%-14s min %9.1f median %9.1f max %9.1f us\n", name, us.front(), us[reps / 2], us.back());
}
int main() {
constexpr int n = 1'000'000;
std::mt19937_64 rng(42);
std::uniform_real_distribution<double> u(0.0, 1.0);
std::vector<double> vec(n);
for (auto& x : vec) x = u(rng);
std::list<double> lst(vec.begin(), vec.end());
bench("unused result", [&] { double s = std::accumulate(vec.begin(), vec.end(), 0.0); (void)s; });
bench("vector sum", [&] { do_not_optimize(std::accumulate(vec.begin(), vec.end(), 0.0)); });
bench("list sum", [&] { do_not_optimize(std::accumulate(lst.begin(), lst.end(), 0.0)); });
}
Compiled with c++ -std=c++20 -O2 (benchmark optimised code, as it will run in production) on an Apple-silicon laptop, two consecutive runs printed:
unused result min 0.0 median 0.0 max 0.0 us
vector sum min 1021.8 median 1608.6 max 75902.1 us
list sum min 1483.6 median 2346.3 max 32565.2 us
unused result min 0.0 median 0.0 max 0.0 us
vector sum min 1007.5 median 1602.8 max 3322.9 us
list sum min 1416.7 median 2144.6 max 3126.2 us
Your numbers will differ; the patterns are the point.
- Dead-code elimination. "Unused result" takes 0.0 µs: the compiler deleted the whole sum. Without the barrier you would conclude that summing a million numbers is free.
- Outliers. One run of the vector sum took 75.9 ms against a median of 1.6 ms, an interruption 47 times the typical cost. The mean of that run would be badly distorted; the median and minimum are stable across the two runs.
- Min versus median. The gap between 1.0 ms and 1.6 ms on an idle laptop is frequency scaling and core migration. On a pinned, fixed-frequency machine the two converge.
- Interpreting the result. About 1 ns per element for the vector: a strict left-to-right floating-point sum is a chain of dependent additions, limited by add latency rather than memory bandwidth. The list is only about 1.4 times slower here because its nodes were allocated one after another and sit nearly contiguously in memory; a list built in random order, or after heavy allocation churn, would be far slower. A benchmark measures your data layout as much as your algorithm.
Is the difference real?
Treat repeated timings of A and B as two samples and test the difference. With roughly normal per-run noise, Welch's t-statistic is
Timings are skewed, so a rank test (Mann–Whitney U) or a bootstrap of the difference in medians is often safer. Two practical rules matter more than the choice of test:
- Interleave the runs (A, B, A, B, ...) or randomise their order, so slow drifts such as thermal throttling hit both equally.
- Repeat whole processes, not just iterations inside one process: layout and address randomisation differ per process, and that variation is part of the noise a real change must beat.
Worked example
is a 3% speed-up significant?
A refactor of a pricing routine is benchmarked in 20 interleaved process runs each. Old: mean 1.60 ms, standard deviation 0.10 ms. New: mean 1.55 ms, standard deviation 0.12 ms. Is the improvement significant at the 5% level? How many runs per version would give if the true means and spreads are as observed?
Show solutionHide solution
Standard error of the difference.
Statistic. . The Welch degrees of freedom are about 36.8, and the two-sided p-value is about 0.16. Not significant: a 0.05 ms difference is well inside what noise produces with 20 runs each.
Runs needed. With runs each, , and requires
so about 40 runs per version. With 200 runs each, (), which would settle it, provided the runs are interleaved so drift cannot masquerade as an effect.
Out loud in an interview: "Twenty runs give a standard error of 0.035 ms, so a 0.05 ms gap is 1.4 standard errors, not conclusive. I would interleave runs, double the count, report the medians with a bootstrap interval, and also check the instruction count or cache-miss counters to see whether there is a mechanism for the speed-up."
Knowledge check
A benchmark of a new hash function reports 0.3 ns per call at -O2, far faster than expected. The loop computes the hash of a constant string and ignores the result. What is the most likely explanation?
Knowledge check
Across 50 runs of a function, the timings are mostly 2.0–2.1 ms with three runs at 9 ms. For comparing two implementations of the code path, which summary is most appropriate?
Knowledge check
You benchmark version A for ten minutes, then version B for ten minutes, on a laptop. B looks 4% faster. What is the main flaw?
Key takeaways
- Warm up, repeat, and report a robust statistic (median or minimum) with the spread.
- Keep the computation alive: use run-time inputs and a DoNotOptimize-style barrier.
- Benchmark optimised builds with realistic data; data layout and cache behaviour often dominate.
- Decide whether a difference is real with a test (Welch, Mann–Whitney or bootstrap) on interleaved, multi-process runs.
- Google Benchmark handles iteration counts and repetitions; experimental design is still your job.
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).