Skip to content
systemcoding.dev
Performance

Use hyperfine Warmups, Prepare Commands and Parameter Scans

Control hyperfine 1.19 with --warmup, --prepare, --setup, --cleanup and --parameter-scan to measure cold and warm runs and sweep threads or compilers.

7 min read
Summarize in AI
Flat illustration of a terminal session, with the C, C++ and Ubuntu logos.

The basic hyperfine invocation measures a command the same way each time: run it, record, repeat. Real questions are more specific. How slow is the program with a cold file cache? How does the time change as the thread count goes from one to sixteen? Which of three compilers produced the fastest binary? hyperfine answers each with an option that controls what happens around the measured command. This post covers --warmup, --prepare, --setup, --conclude and --cleanup, then parameter scans with --parameter-scan and --parameter-list, using hyperfine 1.19 on Linux and a small C program. It builds on timing command-line programs with hyperfine and assumes the basic output is familiar.

The program under test

A compression-like workload reads a file, counts byte frequencies in parallel and prints the most common byte. It takes the thread count as an argument:

freq.cc
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

#define MAX_THREADS 64

static unsigned char *data;
static size_t length;
static unsigned long counts[MAX_THREADS][256];
static int nthreads;

static void *work(void *arg)
{
    long t = (long)arg;
    size_t lo = length * t / nthreads;
    size_t hi = length * (t + 1) / nthreads;
    for (size_t i = lo; i < hi; i++)
        counts[t][data[i]]++;
    return NULL;
}

int main(int argc, char **argv)
{
    if (argc != 3) {
        fprintf(stderr, "usage: freq FILE THREADS\n");
        return 2;
    }
    nthreads = atoi(argv[2]);
    if (nthreads < 1 || nthreads > MAX_THREADS)
        return 2;

    FILE *f = fopen(argv[1], "rb");
    if (!f)
        return 1;
    fseek(f, 0, SEEK_END);
    length = (size_t)ftell(f);
    rewind(f);
    data = malloc(length);
    if (fread(data, 1, length, f) != length)
        return 1;
    fclose(f);

    pthread_t th[MAX_THREADS];
    for (long t = 0; t < nthreads; t++)
        pthread_create(&th[t], NULL, work, (void *)t);
    for (int t = 0; t < nthreads; t++)
        pthread_join(th[t], NULL);

    unsigned long total[256] = {0};
    for (int t = 0; t < nthreads; t++)
        for (int b = 0; b < 256; b++)
            total[b] += counts[t][b];

    int best = 0;
    for (int b = 1; b < 256; b++)
        if (total[b] > total[best])
            best = b;
    printf("%d\n", best);
    return 0;
}

Build it and make a test file of 512 MiB filled with a repeating pattern, using standard tools:

Shell
gcc -O2 -pthread freq.c -o freq
head -c 536870912 /dev/zero | tr '\0' 'a' > big.txt

Every byte is a, which is 97, so the program prints:

Text
97

Warm-up: prime the caches

--warmup N runs the command N times before the measured runs and throws the timings away. For this program the first run reads big.txt from disk, and later runs read it from the operating system's page cache, which is much faster. If you want the warm-cache cost, warm up:

Shell
hyperfine --warmup 2 './freq big.txt 4'

Without it, the first run is slower and hyperfine warns that the first run was significantly slower than the rest. A warm-up is the right answer when the steady state is what you care about.

Prepare: reset state before every run

When you want the cold-cache cost, the file cache must be dropped before each timed run, not once. --prepare runs a command before every timing run, and its time is not counted:

Shell
hyperfine --prepare 'sync; echo 3 | sudo tee /proc/sys/vm/drop_caches' './freq big.txt 4'

Writing 3 to /proc/sys/vm/drop_caches frees the page cache, dentries and inodes, and sync flushes dirty data first so more can be dropped. The command needs root, so use sudo or run the whole benchmark as root. Dropping caches affects the whole machine, so do not do this on a shared server. With a prepare command, hyperfine does not warm up automatically in a way that defeats the preparation: the preparation runs before the warm-up runs too, so each warm-up also starts cold, which is usually what you want to mean by "cold".

You can give one --prepare per command, when comparing commands that need different setup. The number of prepare options must be one, applied to all, or equal to the number of commands.

Setup, conclude and cleanup

Three more hooks run once or around groups of runs. --setup runs once per benchmark before any timing, and is the place to build the program or create the input. --conclude runs after every timing run, which is useful for removing a file the run created. --cleanup runs once after all runs of a benchmark:

Shell
hyperfine \
  --setup 'gcc -O2 -pthread freq.c -o freq' \
  --warmup 1 \
  --cleanup 'rm -f freq' \
  './freq big.txt 4'

Putting the compile in --setup guarantees the binary exists and is current, and keeps the compile time out of the measurement. For commands that compare two builds, give each its own setup using the same one-per-command rule.

Parameter scan over numbers

--parameter-scan substitutes a numeric range into the command for each value. The placeholder is written in braces, and you give it a name, a start and an end, with an optional step:

Shell
hyperfine --warmup 2 --parameter-scan threads 1 8 './freq big.txt {threads}'

hyperfine runs the benchmark eight times, one per value, and reports each:

Text
Benchmark 1: ./freq big.txt 1
  Time (mean ± σ):     398.2 ms ±   4.9 ms    [User: 241.6 ms, System: 156.3 ms]
  Range (min ... max):   391.0 ms ... 407.4 ms    10 runs

Benchmark 2: ./freq big.txt 2
  Time (mean ± σ):     262.5 ms ±   3.8 ms    [User: 251.0 ms, System: 171.4 ms]
  Range (min ... max):   257.1 ms ... 269.9 ms    10 runs

...
Summary
  ./freq big.txt 6 ran
    1.02 ± 0.02 times faster than ./freq big.txt 7
    1.03 ± 0.02 times faster than ./freq big.txt 8
    1.07 ± 0.03 times faster than ./freq big.txt 5

The data is illustrative. A scan like this typically shows time falling as threads are added and then flattening, where the limit moves from computation to reading the file and memory bandwidth. The plateau tells you the useful thread count. Export the results as JSON with --export-json and plot time against threads. To scan with a step, add it as a fourth number, --parameter-scan threads 2 16 -D 2, where -D sets the step size.

Parameter list over names

For non-numeric variations, --parameter-list takes a name and a comma-separated list of values. Comparing compilers or optimization flags is the classic use:

Shell
hyperfine --warmup 2 \
  --setup 'gcc -O2 -pthread freq.c -o freq_gcc; clang -O2 -pthread freq.c -o freq_clang' \
  --parameter-list build gcc,clang \
  './freq_{build} big.txt 4'

Each value of build replaces {build} in the command, producing two benchmarks that appear in the same summary with a relative ratio. You can pass several lists, and hyperfine takes their product, so -L opt O1,O2,O3 -L threads 1,4 runs six combinations. Keep the product small, since each combination runs the full number of repetitions.

Pitfalls

The most common problem is a prepare command that fails silently. If it exits with a nonzero status, hyperfine stops with an error rather than measuring a command with the wrong state, which is the right behavior, so do not add -i without a reason. A second pitfall is putting a long compile inside the measured command, which swamps the quantity you wanted. A third is measuring too few runs when the spread is large: parameter scans multiply the total time, so the temptation is to lower --runs, and the cost is wider intervals. Fix the noise first. Finally, remember that a prepare that drops the page cache also slows every following command on the machine for a moment, and results can differ between a spinning disk, a SATA solid-state drive and NVMe.

Combine hooks in a repeatable script

The options compose, and the combination is what makes a benchmark repeatable. A complete cold-start comparison of two builds across thread counts looks like this:

cold-scan.shShell
#!/usr/bin/env bash
set -euo pipefail

hyperfine \
  --setup 'gcc -O2 -pthread freq.c -o freq' \
  --prepare 'sync; echo 3 | sudo tee /proc/sys/vm/drop_caches > /dev/null' \
  --runs 10 \
  --parameter-scan threads 1 8 \
  --export-json cold-scan.json \
  './freq big.txt {threads}'

Every run starts with an empty page cache, so every run pays the cost of reading the file from storage, and the thread count then shows how much of that cost parallel counting can hide. Compare the output with a second run that uses --warmup instead of --prepare to see the same scan with a warm cache. The difference between the two is the storage cost, which no amount of CPU optimization removes.

Check what the numbers say

A parameter scan produces a lot of numbers, and the summary only ranks them. Plot time against the parameter from the JSON file, and read the shape. A curve that falls and flattens shows diminishing returns, and the knee is where you stop adding threads. A curve that falls and then rises shows overhead overtaking the gain, as when many threads contend for one lock or one memory channel. A flat curve means the parameter does not matter, and the work is limited by something else, such as input reading. The shape tells you more than any single point.

Share

Keep reading

Flat illustration of two options weighed side by side, with the C, C++ and Rust logos.
Performance

Spinlocks vs Mutexes: When Spinning Wins

A spinlock burns a core while it waits and a mutex sleeps. Compare their costs, write a correct C11 spinlock, and see when user-space spinning beats a mutex.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.