The Complete Guide to Benchmarking Native Code Correctly
Measure C, C++, Rust and Go the right way: clocks, optimizer barriers, warm-up, statistics, environment control, frameworks and reporting, with working code.

Almost every performance decision rests on a measurement, and almost every first measurement is wrong. A timing loop prints a number, the number looks reasonable, and a decision follows. Weeks later someone reruns it on another machine and gets half the result, or finds that the function being timed was deleted by the compiler, or that the first run was ten times slower than the rest. None of these is exotic. They are the ordinary failure modes of benchmarking native code, and they have known causes and known fixes. This guide teaches the whole method in order: what you are measuring, how to read a clock, how to keep the optimizer honest, how to warm up and repeat, how to summarize noisy data, how to control the machine, which tools to use for C, C++, Rust and Go, and how to report a result so someone else can trust it. Every section has code that you can adapt, written for GCC 14, Clang 19, Rust 1.83, Go 1.24 and Linux with a 6.12 kernel, and each section links to a focused post when you need more depth.
If you only have a minute: use a monotonic clock, make results observable so the compiler cannot delete the work, discard a warm-up, repeat many times, summarize with the median or minimum, fix the machine's state, compare versions interleaved, and always look at the generated code once. The rest of the guide explains why each rule exists and how to follow it.
Start with the question, not the stopwatch
A benchmark answers a question, and the question decides everything else. Before writing any code, finish this sentence: "I want to know how long X takes when Y." The two blanks carry most of the design.
X is the operation. It might be a function, a data structure operation, a request, a whole program or a phase of one. The smaller X is, the more a measurement is dominated by the harness and by the state of the machine. A function that takes five nanoseconds cannot be timed with a clock that costs twenty, and has to be timed in batches. A whole program that takes a second is easy to time but tells you little about which part to change.
Y is the condition. Does the data fit in cache or not? Is the machine otherwise idle or loaded? Is this the first call or the millionth? Is the input sorted, random, or a realistic mix? Are you comparing versions of your own code or comparing against someone else's? A number without its condition is not a result. "Sorting takes 40 milliseconds" means nothing until you add "for a million random 32-bit integers, warm cache, one core, at 3.6 GHz".
Then decide which quantity answers the question. There are four common ones:
| Quantity | Meaning | When it fits |
|---|---|---|
| Latency | Time for one operation, start to finish | A request a user waits for; a call on the critical path |
| Throughput | Operations completed per unit time | Batch work; a pipeline's capacity |
| Cycles per element | Processor cycles per item processed | Loops over data; comparing machines and code generation |
| Resource use | Memory, allocations, instructions retired | Explaining why a time is what it is |
Latency and throughput are related but not the same. A pipeline that overlaps work has high throughput and unchanged latency per item. When people say "faster", find out which they mean. This guide measures mostly latency and throughput in a loop, and cycles per element where that is more informative.
Finally, decide what decision the result feeds. "Is the new parser at least 20 percent faster?" needs a different level of care than "roughly how long does this take?" A sentence like that sets how many runs you need, how quiet the machine must be and how you will report uncertainty. Write it at the top of your benchmark source as a comment. It keeps you honest when the numbers come out in an inconvenient direction.
Choose a clock you can trust
A benchmark needs a way to read elapsed time, and the wrong clock gives wrong answers in ways that are hard to notice.
The first requirement is that the clock is monotonic: it never goes backward. The wall clock, the one that tells you the date, can be adjusted by NTP or by an administrator while your program runs, and an interval measured with it can be negative or wildly wrong. On POSIX systems use clock_gettime with CLOCK_MONOTONIC. In C++ use std::chrono::steady_clock, which is the standard's monotonic clock, and never system_clock for intervals. In Rust use std::time::Instant, and in Go the time.Now() value carries a monotonic reading that time.Since uses. In Zig, std.time.Timer.
The second requirement is resolution fine enough for your interval. Linux reports nanosecond resolution for CLOCK_MONOTONIC, but the useful resolution is limited by the cost of reading it. On x86-64 the read is served from the vDSO, a small region of kernel-provided code mapped into your process, so it does not enter the kernel, and it costs tens of nanoseconds. On virtual machines whose clock source falls back to something slower, a read can cost hundreds of nanoseconds or more. Check what you have:
cat /sys/devices/system/clocksource/clocksource0/current_clocksourcetsctsc means reads use the processor's time stamp counter and are cheap. Names such as hpet or acpi_pm mean reads are slow, and you should batch more.
Measure the clock's own cost, because it sets the smallest interval you can time sensibly. Read it twice in a row and take the smallest difference:
#include <stdint.h>
#include <stdio.h>
#include <time.h>
static inline uint64_t now_ns(void)
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (uint64_t)ts.tv_sec * 1000000000ull + (uint64_t)ts.tv_nsec;
}
int main(void)
{
uint64_t best = ~0ull;
for (int i = 0; i < 100000; i++) {
uint64_t a = now_ns();
uint64_t b = now_ns();
if (b - a < best)
best = b - a;
}
printf("smallest back-to-back difference: %llu ns\n", (unsigned long long)best);
return 0;
}smallest back-to-back difference: 19 nsThe figure is illustrative. If your clock costs about 20 nanoseconds, then timing a single operation that takes 20 nanoseconds produces a measurement that is half harness. The fix is batching: time a loop of a thousand calls and divide. The overhead becomes one part in a thousand. The rule of thumb is to make each timed interval at least a few hundred times longer than the clock cost, which for most machines means timing intervals of several microseconds or more.
For cycle-level work on x86-64 there is also the time stamp counter, read with rdtsc. It counts at a constant reference rate on modern chips, not at the core's actual clock, and it needs serializing instructions around it to be accurate. The post on writing a harness that reports cycles per element covers it, along with the conversion between reference cycles and core cycles.
Do not use clock() from time.h for this. It measures processor time with coarse resolution, and it sums all threads, which confuses the interpretation of parallel code. Do not use gettimeofday or time. Do use the process CPU clock, CLOCK_PROCESS_CPUTIME_ID, when you specifically want CPU time rather than elapsed time, and record both when the code might block: a large gap between wall time and CPU time says the code spent time waiting, not computing.
Keep the optimizer from deleting your benchmark
An optimizing compiler's job is to produce a faster program with the same observable behavior. A benchmark's measured work usually has no observable behavior, so a good optimizer removes it. This is the single most common reason that a benchmark reports an impossibly small number.
There are four ways the optimizer can defeat you.
Dead code elimination. If the result of a computation is never used, the computation can be removed. A loop that calls a pure function and ignores the result becomes an empty loop, and an empty loop is removed too.
Constant folding. If the inputs are compile-time constants and the function is visible, the compiler evaluates the function at compile time. The benchmark then measures the loading of a constant.
Loop-invariant hoisting. If the call's inputs do not change between iterations and the function has no side effects, the compiler computes it once before the loop and reuses the result.
Closed-form replacement. Modern compilers recognize some loops, such as summing integers or squares, and replace them with a formula. The cost no longer depends on the loop count.
See all four in one place:
#include <stdint.h>
#include <stdio.h>
#include <time.h>
static uint64_t sum_squares(uint32_t n)
{
uint64_t total = 0;
for (uint32_t i = 0; i < n; i++)
total += (uint64_t)i * i;
return total;
}
int main(void)
{
struct timespec t0, t1;
clock_gettime(CLOCK_MONOTONIC, &t0);
for (int r = 0; r < 1000000; r++)
sum_squares(1000);
clock_gettime(CLOCK_MONOTONIC, &t1);
double ns = (t1.tv_sec - t0.tv_sec) * 1e9 + (t1.tv_nsec - t0.tv_nsec);
printf("%.4f ns per call\n", ns / 1000000);
return 0;
}0.0003 ns per callCompiled at -O2, the loop of a million calls is removed entirely, because sum_squares(1000) is pure, has a constant argument and its result is dropped. The figure printed is the cost of reading the clock twice divided by a million. The program says each call takes a third of a picosecond, which is faster than light could cross the chip.
The remedy has two halves: make the inputs unknown and make the results used. Both are done with a compiler barrier, an empty piece of inline assembly that the compiler must assume reads and writes the values it names:
#ifndef BARRIER_H
#define BARRIER_H
#include <stdint.h>
/* Pretend the compiler cannot see the value: it may have been changed. */
#define OPAQUE(x) __asm__ volatile("" : "+r"(x))
/* Pretend the value is read by something unseen. */
#define USE(x) __asm__ volatile("" : : "r"(x))
/* Pretend any memory may have been read or written. */
#define CLOBBER() __asm__ volatile("" : : : "memory")
/* Keep the compiler from moving work across a clock read. */
#define CLOCK_FENCE() CLOBBER()
#endifOPAQUE(x) forces x into a register and tells the compiler its value is unknown afterward, so it cannot fold or hoist. USE(x) marks a result as consumed, so the computation that produced it stays. CLOBBER() forces memory writes to complete from the compiler's point of view. These cost no instructions of their own, they only constrain the optimizer. Library equivalents exist: Google Benchmark's benchmark::DoNotOptimize and benchmark::ClobberMemory, Rust's std::hint::black_box, and Zig's std.mem.doNotOptimizeAway. The post on stopping the optimizer from deleting benchmarks examines their exact semantics.
The fixed version of the benchmark:
#include <stdint.h>
#include <stdio.h>
#include <time.h>
#include "barrier.h"
static uint64_t sum_squares(uint32_t n)
{
uint64_t total = 0;
for (uint32_t i = 0; i < n; i++)
total += (uint64_t)i * i;
return total;
}
int main(void)
{
struct timespec t0, t1;
uint32_t n = 1000;
clock_gettime(CLOCK_MONOTONIC, &t0);
for (int r = 0; r < 1000000; r++) {
OPAQUE(n);
uint64_t result = sum_squares(n);
USE(result);
}
clock_gettime(CLOCK_MONOTONIC, &t1);
double ns = (t1.tv_sec - t0.tv_sec) * 1e9 + (t1.tv_nsec - t0.tv_nsec);
printf("%.1f ns per call\n", ns / 1000000);
return 0;
}85.0 ns per callThe figure is illustrative; the point is that it is plausible now. OPAQUE(n) inside the loop means n may differ every iteration, so the call cannot be hoisted or folded, and USE(result) keeps its value alive. Even so, a modern compiler may turn the inner loop into a closed formula, in which case the time is a few nanoseconds regardless of n. That would be correct behavior by the compiler and a signal that you are no longer measuring a loop. The way to find out is the next habit.
Read the assembly once
After any change to a benchmark, and always for a new one, look at what the compiler produced for the timed region. This takes thirty seconds and prevents the worst mistakes. Compile with -S and read the function, or use a web compiler explorer with the same compiler version and flags. What you look for:
Is the loop you meant to time present, with the expected number of iterations?
Did the compiler replace it with a closed form, a constant or a call to a library routine?
Did it vectorize? Packed instructions (
addps,paddd,vfmadd231ps) mean it did, and the figure you get is vector throughput.Are the barrier statements where you intended, inside the loop?
For a fast check from the command line:
gcc -O2 -S -fverbose-asm -o - fixed.c | grep -A12 '^main:' | head -n 30or disassemble the binary with objdump -d --no-show-raw-insn -M intel ./fixed. The post on inspecting benchmark assembly shows concrete patterns.
Never "solve" optimizer problems by turning optimization off. A benchmark at -O0 measures code that you will not ship, with different bottlenecks: at -O0 almost everything lives in memory, so the cost is dominated by loads and stores that vanish in the optimized build. Benchmark the optimization level that ships, and use the barriers to keep the work alive within it.
Warm up before you measure
The first execution of any code is unrepresentative. On the first call the instructions are not in the instruction cache, the data is not in the data cache, the branch predictor has no history, page table entries may be missing and pages may need to be faulted in, shared libraries bind their symbols lazily, and the processor may still be climbing from a low frequency to its working one. A benchmark that includes this behavior reports a mixture of warm-up and the work, and the warm-up share depends on how long the benchmark runs.
The fix is simple: run the code several times before you start timing, and discard those runs. How many depends on the code. A warm-up of enough iterations to take tens of milliseconds covers frequency ramping, and a handful of calls covers the caches. The harness later in this guide uses a fixed number of warm-up repetitions.
Whether to warm up is itself a question of what you want to measure. A warm measurement is the right one for steady-state work, such as a loop that runs millions of times on the same data. A cold measurement is right for code that runs once or rarely, such as a command-line tool launched by a user, and there the cold cost, including the page cache and the dynamic linker, is the number that matters. Both are valid, and mixing them up is the error. The post on warm and cold cache benchmarks shows how to produce each deliberately: clflush for the CPU caches and drop_caches for the page cache.
A related effect is the frequency governor. If the processor idles between your runs, it drops to a low frequency and takes milliseconds to climb back. A short benchmark can finish before the climb completes. Warm-up long enough to reach the steady frequency, or fix the frequency as described in a later section.
Repeat, and keep every sample
One measurement is an anecdote. Run the thing many times, and keep each result.
The reason is that any single measurement includes noise from the machine: an interrupt that landed in the interval, a context switch, a cache line evicted by another process, a clock step. Most of this noise can only lengthen a measurement, so a distribution of repeated measurements has a hard floor, near the true cost of the code with no interference, and a long tail upward. The shape matters for what you do next, and the post on measurement noise gives the long version.
Structure the benchmark in two levels. The inner level is a batch: call the operation many times in a loop so that the clock overhead is small and the interval is long enough to measure. The outer level is a repetition: time many batches and keep each one's result. A benchmark with a batch of one thousand calls and two hundred repetitions yields two hundred samples of the per-call time, and from them you can compute statistics.
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "barrier.h"
#define BATCH 1000
#define REPS 200
static uint64_t now_ns(void)
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (uint64_t)ts.tv_sec * 1000000000ull + (uint64_t)ts.tv_nsec;
}
static int cmp_double(const void *a, const void *b)
{
double x = *(const double *)a, y = *(const double *)b;
return (x > y) - (x < y);
}
static uint32_t work(uint32_t x)
{
x ^= x << 13;
x ^= x >> 17;
x ^= x << 5;
return x;
}
int main(void)
{
double samples[REPS];
uint32_t state = 2463534242u;
for (int rep = -10; rep < REPS; rep++) {
uint64_t t0 = now_ns();
for (int i = 0; i < BATCH; i++) {
OPAQUE(state);
state = work(state);
}
uint64_t t1 = now_ns();
USE(state);
if (rep >= 0)
samples[rep] = (double)(t1 - t0) / BATCH;
}
qsort(samples, REPS, sizeof samples[0], cmp_double);
printf("min %.2f median %.2f max %.2f ns per call\n",
samples[0], samples[REPS / 2], samples[REPS - 1]);
return 0;
}min 1.21 median 1.23 max 4.87 ns per callThe numbers are illustrative. The shape is the point: the minimum and median agree to two digits, and the maximum is four times larger, from one batch that an interrupt landed in. The first ten repetitions, indexed from -10 up to -1, are warm-up and are not stored. The OPAQUE(state) before each call and the USE(state) after the loop keep the dependent chain of xorshift steps alive; each call depends on the previous result, so this measures the latency of one step, not its throughput.
Summarize with statistics that suit timing data
Given two hundred samples, what single number do you report? The right answer depends on what the number is for.
The minimum is the closest estimate of the cost with the least interference, because noise only adds time. It is the right summary for comparing two implementations on the same machine, and it is what many microbenchmark harnesses report. Its weakness is that it is an extreme, so it needs many samples to be stable, and it is optimistic for code whose real cost varies with data or contention.
The median is the middle sample. It resists outliers completely: up to half the samples can be wild and it barely moves. For most comparisons it is the safest default.
The mean includes the noise. It is the right choice when you care about the total time across many runs, since total time is the mean times the count. It is a poor choice for comparing code, because a few outliers move it.
The standard deviation and the range tell you how stable the measurement is. A spread of a few percent means you can trust differences larger than that. A spread of twenty percent means the machine was noisy and you should fix the environment before drawing conclusions.
When you compare two versions, compute the ratio of the medians and report an interval for it. A confidence interval from resampling, called a bootstrap, works without assuming any distribution. For a significance test, the Mann-Whitney U test compares the ranks of the two samples and does not assume normality, which suits timing data, and is what Google Benchmark's compare.py and Go's benchstat use. The post on statistics in benchmarks has code and a worked example. The short version is: a difference is credible when the intervals of the two medians do not overlap, or when a rank test gives a small p-value over at least ten samples per version, and it is worth acting on when it is also large enough to matter.
Do not report a single run's mean as the result, and do not average the means of several runs and call it a day. Keep the distribution, summarize it robustly and say how many samples stand behind the summary.
Choose inputs that represent the real workload
A benchmark is a model of your program, and a model is only as good as its inputs. Three properties of the input change the result more than most code changes do.
Size relative to the caches. A loop over 4 KiB of data runs from the L1 cache. The same loop over 64 MiB runs from main memory, and its cost per element can differ by an order of magnitude. If your real data is large, a benchmark with a small input will flatter the code. Sweep sizes that cross the cache boundaries, and plot or tabulate the cost per element. A step in the curve marks a cache level. A frequent use of this is to find the working-set size above which your implementation falls off. The post on benchmarking across input sizes shows the tooling.
Distribution and order. Sorting an already sorted array is the best case for many algorithms, and a hash table with keys that all collide is the worst. Branch-heavy code is sensitive to how predictable the data is: the same loop with random data and sorted data can differ by several times because of branch misprediction. Use data with the statistics of your production data. When you cannot, test both extremes and the middle, and say so.
Repetition of the same input. Calling a function a million times with the same argument trains the branch predictor and caches on that argument, and gives an optimistic result. Vary the input between calls in the way production does, for example by cycling through a prepared array of different inputs.
#include <stdint.h>
#include <stdlib.h>
/* A fixed-seed generator so every run sees the same inputs. */
static uint32_t rng_state = 12345u;
static uint32_t next_random(void)
{
rng_state = rng_state * 1664525u + 1013904223u;
return rng_state;
}
uint32_t *make_inputs(size_t count, uint32_t max_value)
{
uint32_t *v = malloc(count * sizeof *v);
for (size_t i = 0; i < count; i++)
v[i] = next_random() % max_value;
return v;
}Seeding the generator with a constant gives identical inputs on every run, so differences between runs come from the machine and not from the data. When you want to see sensitivity to the data, change the seed deliberately and report the spread.
Always build the inputs outside the timed region. Constructing a large array inside the loop measures the construction as well as the work, and distinct inputs are cheap to prepare once and cycle through.
Control the machine
Everything above concerns the code. The machine adds its own variance, and for a careful measurement you control it. The details differ between systems, but the checklist is the same.
Fix the CPU frequency. Frequency scaling and turbo boost make the same code run at different speeds at different times. On Linux, set the performance governor and disable turbo, as in disabling frequency scaling and turbo boost:
sudo cpupower frequency-set -g performance
echo 1 | sudo tee /sys/devices/system/cpu/intel_pstate/no_turboThe second line applies to systems using the intel_pstate driver. AMD and acpi-cpufreq systems use /sys/devices/system/cpu/cpufreq/boost instead, with the opposite sense: writing 0 disables boost.
Pin the process to a core. The scheduler moves threads between cores, and each move cools the caches. Pin the benchmark with taskset -c 2 ./bench, and for the strongest isolation reserve the core at boot with isolcpus, as in isolating benchmark cores. Choose a core other than CPU 0, and be aware of hyper-thread siblings that share the core's execution units.
Quiet the machine. Stop background services, close browsers and indexers, and do not run two benchmarks at once. A load average that is not near zero when you start is a warning.
Use a machine with a real cooler. Laptops throttle on heat and change power limits with the battery state, so numbers drift. Why laptops make bad benchmark machines explains the mechanisms. If a laptop is all you have, plug it in, cool it, keep runs short and trust only ratios from interleaved runs.
Hold memory layout steady, or sample it. The size of the environment, address space randomization and link order all shift addresses, and with them cache and fetch alignment. Differences of several percent can come from layout alone. Use setarch "$(uname -m)" -R to fix the layout for repeatability, and sample layouts deliberately when making small claims, as in the post on layout bias.
Record the context. The report should say the CPU model, kernel version, compiler and flags, governor, whether turbo was on and the date of the build. Frameworks such as Google Benchmark print part of it. A number without its context cannot be reproduced.
Put it together in a complete harness
The pieces so far fit in one small, reusable harness. It takes a function and a context, runs a warm-up, times many batches, and reports the minimum, median and maximum per-call time. It keeps results alive, makes inputs opaque, and uses a monotonic clock. Save the barriers from earlier as barrier.h and write the harness as bench.h:
#ifndef BENCH_H
#define BENCH_H
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "barrier.h"
typedef uint64_t (*bench_fn)(void *ctx);
static inline uint64_t bench_now_ns(void)
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (uint64_t)ts.tv_sec * 1000000000ull + (uint64_t)ts.tv_nsec;
}
static int bench_cmp(const void *a, const void *b)
{
double x = *(const double *)a, y = *(const double *)b;
return (x > y) - (x < y);
}
static void bench_run(const char *name, bench_fn fn, void *ctx,
int batch, int reps)
{
const int warmup = 10;
double *samples = malloc((size_t)reps * sizeof *samples);
for (int r = -warmup; r < reps; r++) {
uint64_t t0 = bench_now_ns();
for (int i = 0; i < batch; i++) {
uint64_t result = fn(ctx);
USE(result);
}
CLOCK_FENCE();
uint64_t t1 = bench_now_ns();
if (r >= 0)
samples[r] = (double)(t1 - t0) / batch;
}
qsort(samples, (size_t)reps, sizeof *samples, bench_cmp);
printf("%-16s min %9.2f median %9.2f max %9.2f ns (batch %d, reps %d)\n",
name, samples[0], samples[reps / 2], samples[reps - 1], batch, reps);
free(samples);
}
#endifCLOCK_FENCE() is defined in barrier.h as an alias of CLOBBER(), so that the compiler cannot move the clock read above the loop. Now use it. The subject is a function that searches a sorted array of 4096 integers, with a linear scan against a binary search, to show that the right algorithm wins at one size and may not at another:
#include <stdint.h>
#include <stdlib.h>
#include "bench.h"
#define N 4096
struct ctx {
const int32_t *data;
int32_t *keys;
size_t nkeys;
size_t next;
};
static uint64_t linear(void *p)
{
struct ctx *c = p;
int32_t key = c->keys[c->next++ % c->nkeys];
OPAQUE(key);
for (size_t i = 0; i < N; i++)
if (c->data[i] >= key)
return i;
return N;
}
static uint64_t binary(void *p)
{
struct ctx *c = p;
int32_t key = c->keys[c->next++ % c->nkeys];
OPAQUE(key);
size_t lo = 0, hi = N;
while (lo < hi) {
size_t mid = lo + (hi - lo) / 2;
if (c->data[mid] < key)
lo = mid + 1;
else
hi = mid;
}
return lo;
}
int main(void)
{
int32_t *data = malloc(N * sizeof *data);
for (int i = 0; i < N; i++)
data[i] = 2 * i;
size_t nkeys = 1024;
int32_t *keys = malloc(nkeys * sizeof *keys);
uint32_t s = 99;
for (size_t i = 0; i < nkeys; i++) {
s = s * 1664525u + 1013904223u;
keys[i] = (int32_t)(s % (2 * N));
}
struct ctx c = { data, keys, nkeys, 0 };
bench_run("linear", linear, &c, 100, 200);
bench_run("binary", binary, &c, 100, 200);
return 0;
}linear min 861.40 median 874.20 max 1102.60 ns (batch 100, reps 200)
binary min 19.80 median 20.60 max 38.90 ns (batch 100, reps 200)The numbers are illustrative. Three design choices matter here. The keys come from a prepared array and cycle, so each call searches for a different value, which defeats hoisting and avoids training the branch predictor on one key. OPAQUE(key) hides the value from the compiler. And each function returns the position it found, which the harness consumes with USE, so neither search can be deleted. Even so, run both under a disassembler once: a compiler can occasionally unroll or vectorize the linear scan, and you should know whether the 4096-iteration loop you wrote is the loop that ran.
Choose a framework when you outgrow the harness
A hand-written harness is fine for a quick answer, and it is transparent. As a project grows you want things it lacks: automatic choice of iteration counts, repetition aggregation, parameter sweeps, machine-readable output, comparison tools and a community that has already fixed the corner cases. These are the mainstream choices for native code.
C++: Google Benchmark. The standard choice, with a registration macro, a state loop, automatic iteration counts, Range sweeps, complexity fitting, JSON output and a comparison script. Start with writing a first microbenchmark.
#include <benchmark/benchmark.h>
#include <vector>
static void BM_PushBack(benchmark::State &state)
{
for (auto _ : state) {
std::vector<int> v;
v.reserve(1000);
for (int i = 0; i < 1000; i++)
v.push_back(i);
benchmark::DoNotOptimize(v.data());
benchmark::ClobberMemory();
}
}
BENCHMARK(BM_PushBack);
BENCHMARK_MAIN();C++: nanobench and Catch2. nanobench is a single header with hardware counter columns on Linux, and Catch2 puts benchmarks beside unit tests. The post on comparing the three has a decision table.
Rust: Criterion. Statistics-driven, with warm-up, outlier detection and comparison against the previous run. Use std::hint::black_box on inputs.
use criterion::{criterion_group, criterion_main, Criterion};
use std::hint::black_box;
fn bench(c: &mut Criterion) {
let data: Vec<u64> = (0..10_000).collect();
c.bench_function("sum", |b| {
b.iter(|| black_box(&data).iter().sum::<u64>())
});
}
criterion_group!(benches, bench);
criterion_main!(benches);Go: the testing package. Built in. Write func BenchmarkX(b *testing.B) with a b.Loop() loop in Go 1.24, run go test -bench=. -benchmem, and compare runs with benchstat.
package main
import "testing"
func BenchmarkSum(b *testing.B) {
data := make([]int, 10000)
for i := range data {
data[i] = i
}
for b.Loop() {
total := 0
for _, v := range data {
total += v
}
_ = total
}
}Whole programs: hyperfine. For command-line tools, time the entire process with warm-ups and statistics, as in timing programs with hyperfine.
| Situation | Reach for |
|---|---|
| A C function, no dependencies wanted | A small hand-written harness, as above |
| C++ function with sweeps, threads, comparison | Google Benchmark |
| C++ quick check, single header | nanobench |
| Benchmarks alongside C++ unit tests | Catch2 |
| Rust crate | Criterion |
| Go package | testing and benchstat |
| Zig | std.time.Timer with doNotOptimizeAway |
| A command-line tool end to end | hyperfine |
| Cortex-M firmware | DWT cycle counter harness |
Whichever you pick, the principles of this guide still apply. A framework automates iteration counts and statistics. It cannot see that your input is a constant, that the machine is throttling or that your benchmark measures the wrong thing.
Understand what a microbenchmark can and cannot tell you
A microbenchmark isolates a small operation and measures it precisely. That precision is useful and dangerous. It is useful because you can detect small changes and understand a mechanism: why one loop form beats another, what a cache miss costs, how a data structure scales. It is dangerous because the isolation removes the context that matters in a real program.
In a real program the function runs among other code. Its instructions compete with other code for the instruction cache, its data was last touched some time ago, its branches are predicted from a history shaped by what ran just before, and its memory allocations interact with everything else the allocator serves. A microbenchmark has hot caches, a trained predictor and a quiet allocator, and it reports the best case. A function that wins by thirty percent in isolation may win by nothing in the program, or lose, if its extra code size pushes something else out of the instruction cache.
A practical stance is to use microbenchmarks to learn and to screen, and macro benchmarks to decide. A macro benchmark is the whole program, or a representative slice of it, run on realistic data. When the micro result and the macro result agree, you have confidence. When they disagree, the macro result wins, and the disagreement is a finding: something in the context matters. Keep both. A profile of the real program, from perf or a similar tool, tells you which functions deserve a microbenchmark in the first place, so you do not tune what does not matter.
Amdahl's law is the arithmetic behind this: if a function accounts for 5 percent of the runtime, making it ten times faster improves the program by about 4.5 percent, however impressive the microbenchmark. Check the share before optimizing.
Compare two versions fairly
Most benchmarks exist to compare: the old code and the new code, or two algorithms, or two compilers. Fair comparison has its own rules, and the common errors all come from the two measurements not being comparable.
Run both on the same machine in the same session. Numbers from different machines, or from the same machine on different days, differ for reasons unrelated to the code.
Interleave the runs. If you run all of version A and then all of version B, any drift in the machine, such as warming up, a background job starting or a thermal limit, lands on one version. Alternate A and B for each repetition so drift affects both equally.
#!/usr/bin/env bash
set -euo pipefail
: > a.txt
: > b.txt
for i in $(seq 1 20); do
taskset -c 2 ./bench_a >> a.txt
taskset -c 2 ./bench_b >> b.txt
doneCheck that both do the same work. Compare outputs. A version that is faster because it skipped part of the job has not improved.
Use a statistical test, and require a margin. Two sets of timings overlap in noise. A rank test such as Mann-Whitney U tells you whether the shift is detectable, and an effect size tells you whether it matters. Tools do this for you: Google Benchmark's tools/compare.py and Go's benchstat both print a significance figure beside the percentage change. The posts on compare.py and benchstat show how to read them.
Change one thing at a time. If you changed the algorithm and the compiler flags together, you cannot say which helped. Hold everything else fixed.
Watch for the build, not only the code. Two compiler versions, two optimization levels or two link orders change the machine code. Report which you used. Layout alone can move a result by a few percent, so for a small claim, test several layouts.
Use hardware counters to explain a time
A time tells you how long. It does not tell you why, and without the why you cannot decide what to do next. Hardware performance counters, built into every modern CPU, count events such as instructions retired, cycles, branch mispredictions and cache misses. Reading them alongside the time turns a number into a diagnosis.
On Linux, perf stat reads them for a whole command:
perf stat -e cycles,instructions,branch-misses,cache-misses ./bench Performance counter stats for './bench':
4,812,330,114 cycles
9,402,118,507 instructions # 1.95 insn per cycle
1,203,481 branch-misses
88,341,022 cache-misses
1.203911344 seconds time elapsedThe figures are illustrative. Read the ratio. Instructions per cycle near the machine's width, which is four to six on current cores, means the code is compute-bound and the way to speed it up is to execute fewer instructions. A low figure, under one, means the core is stalled, usually on memory, and the cause is probably cache misses, which the last line quantifies. A high branch-miss count points to unpredictable branches. Together the numbers say which of three different kinds of problem you have, and each has a different fix.
You can also read counters inside a benchmark framework. Google Benchmark takes --benchmark_perf_counters=CYCLES,INSTRUCTIONS when built with libpfm, as in reading hardware counters in Google Benchmark, and nanobench shows instruction and cycle columns by default on Linux. Instruction counts have a useful property: they are nearly the same on every run, so a change in instructions is a real change in the code, not noise.
Counters need permission. On Linux the gate is kernel.perf_event_paranoid, and virtual machines and containers often hide the counters. When they are unavailable, a simulator such as Cachegrind gives deterministic instruction and cache-miss counts under a simple model, as in simulating cache behavior with Cachegrind.
Measure latency distributions, not only averages
Averages hide the experience of the unlucky. A service whose average response is ten milliseconds can have one request in a hundred take a second. For anything user-facing, latency is a distribution, and the tail percentiles, p99 and p99.9, are the numbers that matter.
Recording every sample costs memory. A histogram with logarithmic buckets, such as HdrHistogram, records values in constant space and answers percentile queries with bounded relative error. Use it in the measuring loop, and report the percentiles: recording latency distributions with HdrHistogram has the code.
struct hdr_histogram *h;
hdr_init(1, 3600LL * 1000000000LL, 3, &h);
/* for each operation: */
hdr_record_value(h, elapsed_ns);
/* afterwards: */
long long p99 = hdr_value_at_percentile(h, 99.0);There is a trap in measuring latency under load. A load generator that waits for each reply before sending the next request stops sending when the system stalls, so it records one slow request instead of the thousand that would have queued up. This is coordinated omission, and it makes tail latencies look far better than they are. The fix is to schedule requests by their intended start times and measure latency from the intended time, as in coordinated omission and your p99. Single-threaded function benchmarks do not have this problem, since there is no arrival process, but anything modeling a service does.
Benchmark firmware and embedded targets
A microcontroller has no operating system noise, which is an advantage, and a set of hidden state variables that make repeated measurement just as treacherous: interrupts, instruction and data caches on the larger cores, flash wait states and prefetch buffers, and DMA traffic on the bus. The tools are different, with a cycle counter instead of a wall clock, but the method is the same: control the state, repeat, and report a spread.
On Arm Cortex-M3, M4, M7 and M33, the DWT cycle counter counts processor cycles, which makes results independent of clock settings:
CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
DWT->CYCCNT = 0;
DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk;
uint32_t t0 = DWT->CYCCNT;
kernel();
uint32_t cycles = DWT->CYCCNT - t0;Mask interrupts around the region, state whether caches were on, warm or cold, and fix flash wait states or run from tightly coupled memory for a reproducible reference. Benchmarking firmware reproducibly works through it.
On Linux-based embedded boards, build a cross-compiled perf and record on the target, then analyze on the host, as in profiling embedded Linux targets.
Run benchmarks in continuous integration without false alarms
A benchmark nobody runs is a benchmark that rots. Putting it in CI is the way to catch regressions as they land, and the way to get alarm fatigue if you do it carelessly. Shared virtual machines add noise from other tenants, so absolute timings fluctuate by tens of percent.
Three techniques make it work. Count instructions instead of time where you can, since instruction counts are deterministic: run the benchmark under Cachegrind or Callgrind and compare the instruction totals. Compare base and head in the same job, interleaved, so both versions see the same machine, and never compare against a number saved from an earlier run. And require both statistical significance and a margin: fail the build only when the change is detectable and larger than, say, five percent, and only after reporting without failing for a few weeks to learn your false-positive rate. Running benchmarks in CI has the workflow and a decision script.
Keep results from the main branch as artifacts, with the machine's description, so that slow creep, a one percent loss per merge that no single comparison would flag, shows up on a chart.
Report results so others can trust them
A benchmark result is a small piece of evidence, and like any evidence it should come with enough context to be checked. A good report has:
The claim, in one sentence, with the quantity and the condition: "Parsing a 10 MB JSON file takes a median of 41 ms, warm cache, one core."
The comparison, if there is one: the ratio of medians and an interval, such as 0.71 with a 95 percent interval from 0.70 to 0.72.
The spread and the sample count: how many repetitions, and the minimum and maximum or an interval.
The environment: CPU model, core count and frequency governor, kernel and compiler versions and flags, whether turbo and ASLR were on, whether the machine was otherwise idle.
The inputs: size, distribution, seed and where to get them.
The method: framework and version, warm-up policy and how the work was kept alive.
The code, or a link to it, so someone can rerun it.
Say what you did not control. If the run was on a laptop, say so. If you measured one layout, say so. Readers extend trust to results whose limits are stated, and withdraw it from results that read as certain.
Do not publish unmeasured figures. A number in a report is either one you measured with a method you can describe, or one you cite from a primary source. Explain performance through mechanisms where you cannot measure: "the strided loop touches one cache line per element" is a statement about the code, not a timing, and it is true regardless of the machine.
Know when benchmarking misleads
Benchmarking is a tool with limits, and the limits are worth stating.
A benchmark measures the machine it ran on. A result on a desktop part says little about a phone, a server or a different generation of the same family, and the ranking of two implementations can flip between them as the cache sizes, vector widths and branch predictors change. If your users run on varied hardware, measure on several.
A benchmark measures the inputs it was given. If production data differs, the result does not transfer. Instrument production, when you can, to collect the real distribution of sizes and values, and benchmark against it.
A benchmark that wins by a margin below the layout spread, or below the noise, has not shown anything. Report it as unresolved, and either collect more data or conclude that the difference does not matter.
Last, a faster function is not always a better one. Code that is faster by using more memory, more instructions in the cache or more power may be slower in a real system under pressure on those resources. Optimize what the profile says matters, verify at the level of the whole program, and keep the simple version when the gain is small.
A checklist to run before you trust a number
Run through these questions every time. Each one maps to a section above, and a "no" is a reason to keep working.
Do I know what I am measuring and under what conditions?
Is the clock monotonic, and is each interval much longer than the clock's cost?
Does the generated code contain the work I meant to time, in a loop of the expected length?
Are inputs opaque to the compiler and results consumed?
Did I discard a warm-up, and is warm or cold the right condition?
Did I repeat enough times that the median and minimum stop moving?
Do the inputs match the real workload in size, order and variety?
Was the machine controlled: frequency, pinning, background load, layout?
If comparing, were the runs interleaved, the outputs checked and a test applied?
Did I report the spread, the sample count and the environment?


