Why Naive Timing Loops Lie: Common Benchmarking Mistakes
A timing loop around a function can report zero, the wrong function or noise. Learn seven mistakes that make native benchmarks lie, with fixes.

The first benchmark nearly everyone writes is a loop that calls a function a million times between two clock reads and divides. It prints a number, the number looks plausible, and the author decides the function costs that many nanoseconds. The trouble is that the number may describe the clock, the optimizer, the page cache or the laptop's fan, and nothing about the function. This post lists the seven mistakes that make a naive timing loop lie, shows each one in C or C++ with GCC 14 and Clang 19 on Linux, and gives the fix. Once you can spot them, the larger picture in the guide to benchmarking native code falls into place.
Mistake 1: the optimizer deletes the work
Compilers remove code whose result is never used. A benchmark that computes a value and ignores it measures nothing, and at -O2 it measures an empty loop:
#include <stdio.h>
#include <time.h>
static int square(int x) { return x * x; }
int main(void)
{
struct timespec t0, t1;
clock_gettime(CLOCK_MONOTONIC, &t0);
for (int i = 0; i < 100000000; i++)
square(i);
clock_gettime(CLOCK_MONOTONIC, &t1);
double ns = (t1.tv_sec - t0.tv_sec) * 1e9 + (t1.tv_nsec - t0.tv_nsec);
printf("%.3f ns per call\n", ns / 100000000);
return 0;
}0.000 ns per callThe exact output on your machine will be a few thousandths of a nanosecond or exactly zero, because square has no side effects, its result is unused, and GCC deletes the whole loop. The fix is to make the result observable. The portable way in C is to accumulate into a variable that is later printed, or to store into a volatile object:
volatile int sink;
/* inside the loop: */
sink = square(i);In C++ with Google Benchmark, use benchmark::DoNotOptimize, covered in stopping the optimizer from deleting benchmarks.
Mistake 2: the optimizer hoists the work out of the loop
A subtler version leaves the call in the source but lets the compiler compute it once. If the input does not change between iterations, a pure function can be evaluated before the loop. The timing then covers one call plus a loop of nothing. The fix is to make the input change each iteration, and to make the compiler unable to see through it, for instance by reading it from an array filled at run time.
Mistake 3: you timed the first call
The first call to anything pays for things later calls do not: page faults on first touch of memory, instruction cache and branch predictor warm-up, lazy symbol binding in the dynamic linker, and CPU frequency ramp-up. A benchmark that runs once and reports the time reports mostly those. Run a warm-up phase that you discard, then measure many repetitions. If cold behavior is what you want, measure it deliberately, as warm versus cold cache benchmarks explain.
Mistake 4: one measurement, no spread
A single number hides how much it varies. Run the same benchmark five times and you typically get five different results, because other processes, interrupts and frequency changes perturb each run. Reporting the mean of one run says nothing about whether a later 3 percent change is real. The minimum of many runs estimates the cost without interference. The median resists outliers, and the full distribution tells you whether you can trust either. Always repeat, and always report a spread. Measurement noise covers the statistics.
Mistake 5: the clock is too coarse or the wrong kind
Reading the clock costs time too, and a clock with coarse resolution cannot time a short operation. Timing a single 20-nanosecond call with a clock that ticks every microsecond gives either zero or a thousand. The usual cure is to time a batch of calls and divide, which amortizes the clock overhead. Use a monotonic clock, CLOCK_MONOTONIC through clock_gettime, never time() or gettimeofday(), which can jump when the system time is adjusted. In C++ use std::chrono::steady_clock, not system_clock.
#include <chrono>
#include <cstdio>
int main()
{
using clock = std::chrono::steady_clock;
auto a = clock::now();
auto b = clock::now();
auto ns = std::chrono::duration_cast<std::chrono::nanoseconds>(b - a).count();
std::printf("empty interval: %lld ns\n", static_cast<long long>(ns));
return 0;
}empty interval: 21 nsThe figure is illustrative and varies by machine and kernel; on x86-64 Linux the clock is read through the vDSO without entering the kernel, and an empty interval commonly measures tens of nanoseconds. Anything you time that takes less than a few hundred nanoseconds needs batching.
Mistake 6: the machine changed under you
CPU frequency scaling and turbo boost change the speed of the processor during the run. A benchmark that starts on a cool, boosted core and ends on a hot, throttled one reports different speeds for the first and second halves. Other processes compete for caches and memory bandwidth, and the scheduler moves your thread between cores, losing cache contents. Remedies are to fix the frequency governor, pin the process to a core, close other programs and use a desktop or server rather than a laptop. Disabling frequency scaling shows the commands.
Mistake 7: you measured something other than what you meant
Benchmarks have a habit of exercising the wrong code. A debug build with no optimization times code nobody ships. A loop that allocates inside the timed region times the allocator. A function benchmarked with the same input every time trains the branch predictor on that input, and an input that fits in L1 never touches memory. A benchmark of std::sort on already sorted data measures the best case. Check three things before believing a result. Compile with the optimization level you ship. Look at the generated assembly for the loop to confirm the work is present. And choose inputs with the size and distribution the real workload has.
A corrected loop
Putting the fixes together gives a harness that does not lie in the obvious ways. It builds varied inputs, uses the result, warms up, repeats and reports the minimum:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <time.h>
#define COUNT 4096
#define REPS 200
static int square(int x) { return x * x; }
static double now_ns(void)
{
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return t.tv_sec * 1e9 + t.tv_nsec;
}
int main(void)
{
int *in = malloc(COUNT * sizeof *in);
for (int i = 0; i < COUNT; i++)
in[i] = rand();
volatile int sink = 0;
double best = 1e18;
for (int rep = 0; rep < REPS + 10; rep++) {
double t0 = now_ns();
int acc = 0;
for (int i = 0; i < COUNT; i++)
acc += square(in[i]);
double t1 = now_ns();
sink = acc;
if (rep >= 10 && t1 - t0 < best)
best = t1 - t0;
}
printf("%.3f ns per call (best of %d)\n", best / COUNT, REPS);
free(in);
return 0;
}0.310 ns per call (best of 200)This number is illustrative. At -O2, GCC may vectorize the loop, so the per-call figure can be a fraction of a nanosecond, which is a real property of the compiled loop but not of square as a standalone call. That is mistake 7 again: you must decide whether you mean the throughput of the vectorized loop or the latency of one call, and the harness measures the first.
A checklist before you trust a number
Run through these questions every time you produce a benchmark result, and treat a "no" as a reason to keep working. Did the build use the optimization level that ships? Does the assembly of the timed loop contain the work you meant to measure? Does the time change when the amount of work changes, in the direction the algorithm predicts? Was there a warm-up phase that you discarded? Did you repeat the measurement enough times that the minimum and median stop moving between runs? Did the machine stay in one state, with the clock fixed and no heavy background jobs? Did you verify that the functions you compare return the same answer?
Each question maps to one of the mistakes above. The point of the list is that none of them is exotic. They are the ordinary ways a benchmark goes wrong, and each takes a minute to rule out once you have the habit. A result that passes the whole list is not guaranteed to be right, but a result that has never been checked against it should be treated as an anecdote.
What good results look like
A trustworthy benchmark has a few visible properties. Its numbers are stable: running it twice gives figures within a couple of percent. Its numbers respond to the work: doubling the input roughly doubles the time for a linear algorithm. Its context is recorded: the compiler version, the flags, the CPU model and the machine state are written next to the result, so someone else can reproduce it. And it reports a spread, not a bare mean. When you read other people's benchmarks, look for these properties first, since a fast number with none of them tells you very little.


