Benchmark C Code Without a Framework Using clock_gettime
Build a small, correct C benchmark harness with clock_gettime(CLOCK_MONOTONIC), a compiler barrier, warm-up, many repetitions and a median in eighty lines.

C has no standard benchmarking framework, and for a small project adding a dependency to time one function is more trouble than it is worth. The alternative is to write the harness yourself, and the risk is writing one that reports nonsense. The pieces that matter are few: a monotonic clock, a barrier that stops the compiler deleting your work, a warm-up, many repetitions and a summary statistic that ignores outliers. This post builds that harness in under a hundred lines of C11 with GCC 14 on Linux, tests it on two ways of summing an array, and explains each design choice. It is the framework-free version of what Google Benchmark does for C++.
Choose the clock
POSIX clock_gettime takes a clock id and fills in a struct timespec. The right id for measuring intervals is CLOCK_MONOTONIC, which counts from an unspecified point, never goes backward and is not affected by someone setting the system time. CLOCK_REALTIME is wall-clock time and can jump when NTP corrects it, which makes an interval negative or huge. CLOCK_MONOTONIC_RAW is not slewed by NTP at all, which matters for very long measurements, but CLOCK_MONOTONIC is the usual choice. On x86-64 Linux, clock_gettime for these clocks is served from the vDSO, a page of kernel-supplied code mapped into your process, so a call does not enter the kernel. Its cost is still tens of nanoseconds, so you never time one tiny operation by itself. You time a batch and divide.
Stop the compiler deleting the work
The work in the timed region must have an effect the compiler cannot ignore. Two tools are available in GNU C. An empty asm volatile statement with a memory clobber acts as a compiler barrier, and an input constraint on a register tells the compiler the value is used:
#ifndef BENCH_H
#define BENCH_H
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/* The compiler must assume the value is read and memory may change. */
static inline void use_value(uint64_t v)
{
__asm__ volatile("" : : "r"(v) : "memory");
}
/* The compiler must assume the memory behind p is read and modified. */
static inline void clobber(void)
{
__asm__ volatile("" : : : "memory");
}
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;
}
static int cmp_u64(const void *a, const void *b)
{
uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b;
return (x > y) - (x < y);
}
#endifuse_value marks a computed result as consumed. clobber tells the compiler that memory may have been changed by something it cannot see, which stops it from keeping values in registers across the barrier or hoisting loads out of a loop. Both compile to no instructions, so they add no cost. They work with GCC and Clang. On MSVC you would use a different mechanism, and a portable alternative is storing into a volatile variable, at the price of a real store each time.
The harness
The harness runs a function reps times, each time executing it batch times between two clock reads, then reports the median per-call time. A warm-up of a few reps is run and discarded:
#include "bench.h"
typedef uint64_t (*bench_fn)(void *ctx);
static void run_bench(const char *name, bench_fn fn, void *ctx,
int batch, int reps)
{
const int warmup = 5;
uint64_t *samples = malloc((size_t)reps * sizeof *samples);
for (int r = 0; r < warmup + reps; r++) {
uint64_t t0 = now_ns();
for (int i = 0; i < batch; i++) {
uint64_t result = fn(ctx);
use_value(result);
}
clobber();
uint64_t t1 = now_ns();
if (r >= warmup)
samples[r - warmup] = t1 - t0;
}
qsort(samples, (size_t)reps, sizeof *samples, cmp_u64);
double median = (double)samples[reps / 2] / batch;
double best = (double)samples[0] / batch;
double worst = (double)samples[reps - 1] / batch;
printf("%-14s median %10.1f ns min %10.1f max %10.1f (batch %d, reps %d)\n",
name, median, best, worst, batch, reps);
free(samples);
}The design choices each answer a specific failure. Warm-up reps populate caches and let the CPU reach its steady clock. Batching amortizes the clock read, so the roughly twenty nanoseconds of timing overhead is divided by batch. Storing every sample and sorting gives a median and a range without assumptions. The median resists the occasional slow sample caused by an interrupt, and the minimum is the cleanest estimate of the cost without interference. Reporting all three shows the spread at a glance.
Use it on two functions
The test subjects sum an array of 4096 integers two ways, a plain loop and one unrolled by four with independent accumulators. The second breaks the dependency chain on the single accumulator:
#include "harness.c"
#define N 4096
static uint32_t data[N];
struct ctx { const uint32_t *p; size_t n; };
static uint64_t sum_plain(void *c)
{
struct ctx *x = c;
uint64_t s = 0;
for (size_t i = 0; i < x->n; i++)
s += x->p[i];
return s;
}
static uint64_t sum_unrolled(void *c)
{
struct ctx *x = c;
uint64_t s0 = 0, s1 = 0, s2 = 0, s3 = 0;
size_t i = 0;
for (; i + 4 <= x->n; i += 4) {
s0 += x->p[i];
s1 += x->p[i + 1];
s2 += x->p[i + 2];
s3 += x->p[i + 3];
}
return s0 + s1 + s2 + s3;
}
int main(void)
{
for (size_t i = 0; i < N; i++)
data[i] = (uint32_t)i;
struct ctx c = { data, N };
run_bench("sum_plain", sum_plain, &c, 1000, 101);
run_bench("sum_unrolled", sum_unrolled, &c, 1000, 101);
printf("check %llu %llu\n",
(unsigned long long)sum_plain(&c),
(unsigned long long)sum_unrolled(&c));
return 0;
}Compile it with gcc -std=c11 -O2 -march=native main.c -o main and run it. The harness prints one line per benchmark:
sum_plain median 1020.4 ns min 1011.8 max 1184.9 (batch 1000, reps 101)
sum_unrolled median 611.7 ns min 607.2 max 702.3 (batch 1000, reps 101)
check 8386560 8386560These figures are illustrative; they depend on the CPU and compiler. Two observations are safe regardless. The check line shows both functions compute the same result, which a benchmark should always verify. And the sum of 4096 values must not be evaluated once outside the loop: since fn receives a context pointer and use_value consumes the result, GCC cannot hoist the call out of the batch loop. At -O2 the compiler may inline sum_plain into the harness, and if it can prove ctx is constant, it may compute the answer once. Inspect the assembly with gcc -S if the numbers look too good, and call through a function pointer stored in a volatile or an array to prevent inlining.
Pin the machine and process
A few operating-system settings improve repeatability. Pin the process to one core with taskset -c 3 ./main so the scheduler does not migrate it and cool its caches. Prefer a quiet machine with frequency scaling off, as the post on disabling scaling shows. Raise the priority with nice -n -5 if background work interferes. None of these change the harness, they change the noise.
Measure the harness itself
A good habit is to benchmark an empty function first, to learn the floor. An empty function that returns a constant, run through the same harness, gives the per-call overhead of the loop and the barrier. Any real result close to that floor means the function is cheaper than you can measure with this method, and the batch must be larger or the work heavier. Subtracting the floor is tempting, but it is cleaner to treat it as a resolution limit and only trust differences well above it.
Report in the unit your reader needs
A bare "nanoseconds per call" is hard to compare across machines. Add a derived figure that normalizes the result. For a loop over an array, divide by the element count to get nanoseconds per element, and multiply by the clock frequency to get cycles per element, which is the number to compare against the width of the pipeline. For code that processes bytes, report bytes per second. In the harness above, add the element count as an argument and print median / elements. The extra division costs nothing and turns an isolated number into one a reader can place on a scale.
Know the limits of the clock
On Linux, the resolution of CLOCK_MONOTONIC is one nanosecond as reported by clock_getres, but the practical granularity is set by how long the call takes and by the hardware counter behind it. On x86-64 the clock source is normally the time stamp counter, read in user space through the vDSO, and the call costs on the order of tens of nanoseconds. On some virtual machines, the clock source falls back to a slower one that requires a system call, which makes each read cost hundreds of nanoseconds or more. Check with cat /sys/devices/system/clocksource/clocksource0/current_clocksource. If it says tsc, reads are cheap, and if it says something such as hpet or acpi_pm, batch larger.
#include <stdio.h>
#include <time.h>
int main(void)
{
struct timespec res;
clock_getres(CLOCK_MONOTONIC, &res);
printf("%ld ns\n", res.tv_nsec);
return 0;
}1 nsThe printed value is the nominal resolution, not the cost of reading it. Measure the cost by timing an empty batch with the same harness, as described above.


