Files
sakurac/docs/benchmarks.md
T

580 lines
30 KiB
Markdown
Raw Normal View History

2026-10-26 10:14:11 -05:00
# Plan: benchmarks
Written 2026-10-18, and brought up to date 2026-10-20 for memory without a collector,
fixtures lent by reference, callables taken through `invokable` bounds, and a second probe
on Linux. This is a proposal. std is yours, so the decisions at the end are yours to make.
Nothing is built yet.
**Comes after the ffi plan, now built:** `std::sys` is `system`, and `@foreign` and
`@link` are `extern` sections.
**What it is:** measuring how long code takes, the way `std::testing` checks what it
does:
- functions marked `@bench`, which a runner finds and measures one after another;
- a report of each, as a typical time a round and how much it varied;
- saving what was measured, and comparing a later run with it;
- `keep`, which stops the optimizer from taking away the work being measured.
**Its users:**
- std's containers: `dict` against `hashset`, the interner, sorting, and `vector`
growing. The abstraction and optimization work chose between these by timing by hand;
- the compiler's hot spots that `docs/performance.md` names: hash tables, the lexer's
cost a token, and allocation;
- the optimizer: whether a pass makes code faster, at each `-O` level. The 2026-10-18
passes were measured only by timing whole builds;
- the probes in `tools/`, which time calls, iterators and memory by hand, and check a
ratio between two ways of each;
- JSON, YAML and regex throughput;
- any program, comparing two ways of doing something.
**Probed:** twice, in the scratchpad:
- on 2026-10-18 (`benchprobe/`), on Windows, as executables at `-O2` and `-O0`,
and in the VM;
- on 2026-10-20 (`plans/benchmarks/`), on Linux, the same, pinned to one P-core of an
i5-13420H. Other work kept the machine busy, so its numbers come from the runs where
it was quiet.
The probes covered:
- **The steady clock,** which `instant::now()` reads:
- On Windows, through `QueryPerformanceCounter`, its smallest step is 100 ns. A read
took 30 ns in `-O2` executables, and 58 ns in `-O0` ones.
- On Linux, `CLOCK_MONOTONIC` steps by 1 ns, but std makes a system call for each
read. A read took 211 ns in `-O2` executables, and 293 ns in `-O0` ones. A C program
reading the same clock through the vDSO, as glibc does, took 25 ns.
- **What the optimizer takes away from a loop timed by hand,** in nanoseconds a round,
the best of five runs of 20 million rounds, on Linux on 2026-10-20. The work is three
multiplies and shifts, as a hash finishes a word:
| The loop | `-O2` | `-O0` |
|---|---|---|
| Empty | 0.24 | 0.38 |
| A constant in, the result stored to a global | **0.32** | 3.64 |
| A global read in, the result stored to a global | **0.27** | 3.70 |
| The counter in, the result discarded | **0.24** | 3.61 |
| The counter in, the result stored to a global | 1.79 | 3.65 |
| The counter in, the results summed and printed | 1.96 | 3.85 |
| In and out through a `@foreign def` that gives its argument back, the result stored | 1.79 | 7.75 |
| The same, the result discarded | **0.24** | 7.32 |
| In and out through relaxed atomics | 1.92 | 10.65 |
| The work in a function value read from a global, called each round | 3.20 | 4.88 |
- The bold rows measured an empty loop. The compiler moves work on a constant or a
global out of the loop.
- The compiler drops a result that nothing reads, even through a `@foreign def` with a
body, so going through one hides nothing.
- Relaxed atomics keep the work. Three a round, a store and a load in and a store out,
cost 0.1 ns over storing to a global.
- The 2026-10-18 run on Windows found the same of a constant, a global, and a result
discarded.
- **A runner, written in a program of its own.** It found `@bench` functions through
`declarations()` and `attached`, as `std::testing` finds tests. It doubled the rounds
until a run took 1 ms, then took 51 runs as samples, each giving a time a round. Each
benchmark took 2–3 ms to calibrate and 60–90 ms to sample. A relaxed atomic stood in
for `keep`.
- **Medians on Windows,** on 2026-10-18, over three runs of each executable and one in
the VM:
| Benchmark | `-O2` | VM |
|---|---|---|
| `mixes`, the work above | 0.672–0.673 ns | 22.8 ns |
| `inserts_1000`, into a new `dict` | 4.84–4.85 µs | 159 µs |
| `formats`, interpolating two numbers | 54.10–54.12 ns | 173 ns |
The median absolute deviation was under 0.5% of the median in the executables.
- **Medians on Linux,** on 2026-10-20, over three runs of each executable, and eight to
ten of `links_100`:
| Benchmark | `-O2` |
|---|---|
| `mixes` | 1.92–1.93 ns |
| `inserts_1000` | 35.3–36.0 µs |
| `formats` | 172–173 ns |
| `links_100`, a list of 100 `box`es made and closed | 4.63–4.73 µs, and twice 5.76 µs |
The median absolute deviation was under 1.4% of the median.
- **Allocation no longer splits the samples.** On 2026-10-18, `links_100` made a list
of 100 references from the collector each round. Its median was six times its
fastest sample (3.05 µs and 0.51 µs), since most samples held a collection. With no
collector, its fastest sample is within 1% of its median.
- **A build, or a run, can be off as a whole:**
- Code layout alone moved a result by 13%. `inserts_1000` took 4.85 µs in one `-O2`
build on Windows, and 5.47 µs in a build that only added other benchmarks.
- On Linux, one executable gave `links_100` medians of 4.63–4.73 µs in eight runs
and 5.76 µs in two. Each run's own deviation was under 0.6%.
- **Calibrating can stop early.** In one Linux run, `inserts_1000` stopped doubling at
2 rounds, 75 µs a run, where every other run of the executable stopped at 32. One
slow run while doubling is enough to stop it.
- **Benchmarks in constants:** generic instances, as `@bench const views_u8 :=
views::<u8>;`, worked. A closure in a constant, as
`@bench const inserts_10 := def(b: &mut bencher): void { inserts(b, 10); };`,
worked too.
- **Fixtures, on 2026-10-20:**
- A fixture that closes, given by value to a benchmark the runner calls many times, is
refused: "`words` is closed where its scope ends, so it has one owner and is not
copied out of the place holding it." A test runs once, so `std::testing` can give
its fixture by value.
- Lent as `&F` or `&mut F`, a fixture was made once, lent to every run, and closed
once.
- `type_of(params_of(d)[1])` gives only the reference, and nothing gives the type it
refers to. Two overloads of a generic function, taking `def(&mut bencher, &F): void`
and `def(&mut bencher, &mut F): void`, found `F` from the benchmark itself. A
parameter that isn't a fixture gave the runner's `compile_error`.
- `if const type_of(params_of(d)[1]) is fixture<type_of(params_of(d)[1])>` holds of a
fixture taken by value and not of one lent, so the runner can refuse the first with a
`compile_error` of its own.
- **`batched` taking lambdas, on 2026-10-20:** with `make` and `work` bounded by
`invokable`, the compiler took `b.batched(def() => shuffled(10000), def(v: &mut
vector<u64>) { v.sort(); })`, and inferred `T` from the first lambda.
- **Windows' CPU clocks:**
- `GetThreadTimes` and `GetProcessTimes` step by 15.625 ms, so they can't time a
1 ms sample.
- `QueryThreadCycleTime` counts cycles exactly: 428.7 million in 100 ms busy, about
4.29 GHz. But a cycle's length changes as the processor speeds up and slows down.
## What's there now
- **`std::testing`** (`std/testing.sakura`):
- It finds `@test` functions and constants while compiling, through
`declarations()`, `attached` and `value_of`. It tells their shapes apart with `if
const value_of(d) is def(&mut tester): void` and `params_of`, and reports any other
with `compile_error`.
- It runs each test in a copy of the program: forked on Linux, started again with
`SAKURA_TEST_ONE` on Windows.
- It reads `--only TEXT` and `--here`.
- It gives a test a fixture by value, after the tester, made by the fixture's
`setup(t: &mut tester)`. The test runs once, and the fixture closes where the test
returns, where it's a type that closes.
- **`std::time`:**
- `instant::now()` reads the steady clock: `QueryPerformanceCounter` on Windows, and
`clock_gettime(CLOCK_MONOTONIC)` by a system call on Linux, not through the vDSO.
- `instant - instant` and `elapsed()` give a `duration`, which counts whole
nanoseconds in an `i64`. One divided by another is an `f64`, so `took /
nanoseconds(1)` is the nanoseconds as a real.
- `describe` writes one to two places, as "250ms".
- **No CPU clock.** `sys::clock` reads only `clock_kind::wall` and `clock_kind::steady`.
Nor does std pin a thread to a core: it reads the affinity only to count processors.
- **Nothing that stops the optimizer.** The compiler has no `keep` or anything like it.
As the probe found, a loop timed by hand at `-O2` can measure nothing at all.
- **No collector, and no allocation counts.** Memory is owned, as the README's "Pointers
and memory" says, so there are no collections for a benchmark to account for. Each
block is taken from and given back to free lists as the program goes, and once the
program starts a thread, through a cache of that thread's own. A program still can't
ask how many blocks or bytes it allocated. `run --checks` knows every block, but only
lists those never released, as the program ends.
- **Benchmarks so far are probes timed by hand,** or scripts outside the language:
- `tools/function.sakura`, `tools/iterators.sakura` and `tools/memory.sakura` each time
one loop each way with `instant::now()`, keep the work by printing what it gave, and
check a ratio: a functor held in a `function` costs what a function value does;
adapters given functors are within 10% of `for &x in v`; a `box` costs within a
tenth of `raw_allocate`. Each is built at `-O2` and run pinned to a core with
`taskset`;
- CPU-time medians of whole builds, and profiles of `build -g` compilers through
`tools/profile/`;
- hand-timed loops in a plan's probe, as the random plan's.
## What it needs
1. **Benchmarks marked and found as tests are,** with nothing in the compiler knowing
about them, except `keep`.
2. **A way to keep the work being measured** from being moved or taken away, at every
`-O` level, that costs nothing itself.
3. **Rounds sized to the clock:** enough per sample that Windows' 100 ns clock step, and
a clock read of 30–58 ns there and about 210 ns on Linux, don't matter.
4. **Statistics that ignore outliers:** a median, and how much the samples spread. An
interrupt, a page fault, or another program's work makes a sample slower, never
faster.
5. **Setup that isn't timed:** once for a benchmark, through fixtures, and once a round
for work that uses up its input, such as sorting.
6. **Rates:** bytes a second, where a benchmark says how many bytes a round handles.
7. **Saving and comparing:** whether a change made code faster, slower, or neither,
given the noise.
8. **The same in the VM and as executables,** with the report saying which it is.
## How it fits the rules
- **A benchmark is a function with an attribute,** found by reflection while compiling,
as a test is. One that isn't one of the shapes below is a `compile_error`, which says
which shapes are allowed, as `tester::run` does.
- **`bencher` is plain data,** passed as `&mut bencher`. It owns nothing.
- **Inputs made for a batch belong to the runner,** in a vector it sized before. The
work borrows each one as `&mut T`. They're closed after the clock stops, so closing
isn't timed: the one-owner rule decides when, and the runner decides it's outside the
measurement.
- **Callables are taken as std's adapters take them,** through `invokable` bounds, so a
lambda given to `batched` is compiled for its type. It refers to the benchmark's
locals where they are, allocates nothing, and doesn't outlive the call.
- **A fixture** is made before calibration and closed after the last sample. Neither is
timed. In between it's lent to every run, as `&F` or `&mut F`: a fixture that closes
has one owner, so it can't be given by value to a benchmark run more than once.
- **The runner allocates nothing while timing.** Its vectors of samples are sized
before the clock starts. With no collector, what a benchmark allocates costs it as it
goes, and no pause lands in a later sample.
- **One thread.** Benchmarks run one at a time on the thread that called the runner. A
benchmark may start threads of its own.
- **Not while compiling.** The runner reads the clock, a system call evaluation
refuses, so a constant that runs it is noted as not constant.
- **`keep` changes no value.** A program means the same with every `keep` taken out. It
only limits what the optimizer may assume.
## Layers
### The compiler gains `keep` (decision 4)
```sakura
#! Gives a value back as it is, while the optimizer takes it as unknown. The work
#! making the value is never taken away or moved out of a loop, and nothing is
#! worked out ahead from what it gives back. Memory a reference given to it
#! reaches is taken as read and written. Where the program runs, it costs nothing
#! beyond the value being made, and while compiling it is the value itself.
#! @tparam T The type of the value.
#! @param value The value to keep.
#! @returns The value.
@intrinsic
pub def keep<T>(value: T): T;
```
- A new operation, `keep`, in `compiler/intermediate/code.sakura`, with the traits
`op_calls`. The passes go by an operation's traits, so none moves it, merges it, or
takes it away: `dead.sakura`, `loops.sakura` and `sink.sakura` remove or move only
loads and what `code::removable` allows, which no call is. Numbering doesn't take its
result as its operand, so nothing is folded through it.
- `escapes.sakura` and `keeps.sakura` already take what an intrinsic is given as kept,
so `keep(&buffer)` keeps the buffer in memory with nothing added there.
- `emitter/intrinsics.sakura` emits it.
- Natively it's a move into a register, which the allocator usually removes. In
bytecode it's a move.
### `std::testing` gains (decision 1)
```sakura
#! Marks a function, or a constant holding one, as a benchmark that `bencher::run`
#! measures, as `@test` marks a test.
#!
#! A benchmark is a `def(b: &mut bencher): void` that does its work `b.rounds`
#! times. It may also take a fixture after the bencher, by reference, as
#! `def(b: &mut bencher, text: &sample_text): void`, which is made once before it
#! is measured, lent to every run, and closed after, untimed.
@usage{ on = target::functions | target::constants }
pub struct bench : attribute {
pub val name: strview = ""; #! What the report calls it, which is its path when this is empty.
pub val skip: bool = false; #! Whether it is left out, which the report counts.
}
#! What a benchmark is run with.
pub struct bencher {
pub val rounds: u64; #! How many times to do the work in this run.
pub var bytes: u64; #! How many bytes a round handles, which the report gives a rate of where set.
}
#! Does the work once for each of `rounds` inputs that `make` gives, timing only
#! the work. `make` runs before the clock starts, and what it gave is closed after
#! the clock stops. Each is compiled for the callable given, as a lambda.
pub def bencher::batched<T, M, W>(&mut this, make: M, work: W): void
where M: invokable<def(): T> where W: invokable<def(&mut T): void>;
#! Measures every benchmark of the program, one after another (decision 2), and
#! reports each as it finishes.
#!
#! The arguments may say:
#! - `--only TEXT`: the benchmarks whose name holds the text;
#! - `--time MS`: how long each sample runs at least, 1 by default;
#! - `--samples N`: how many samples are taken, 51 by default;
#! - `--save FILE`: write every sample to the file, as JSON;
#! - `--compare FILE`: compare with the samples saved there (decision 3).
#! @param args The arguments the program was given.
#! @returns The status to stop with: zero unless a benchmark could not run.
pub def bencher::run(args: span<strview>): i32;
```
`std::sys` gains nothing: the steady clock is enough. Two reads a sample of 1 ms are
0.04% of it, even at a system call each on Linux.
## Using it
```sakura
import std;
import std::io;
import std::json;
import std::sys;
import std::testing;
# The work itself, in the loop: for the smallest work, with no call each round.
@bench def hashes_words(b: &mut bencher): void {
for i in 0..b.rounds {
val word := keep(i);
_ = keep(hash(&word));
}
}
# Text read once by a fixture, so reading it isn't timed, and closed after the last
# sample, as the string it holds closes.
struct sample_text : fixture<sample_text> {
var data: string;
}
def sample_text::setup(t: &mut tester): sample_text {
val at := path::parse("bench/sample.json") else (_) { return sample_text {}; };
var text := io::read_file(&at) else (_) {
_ = t.expects(false);
return sample_text {};
};
return sample_text { data = move(&mut text) };
}
# The fixture lent to every run. A rate is reported.
@bench def parses_json(b: &mut bencher, text: &sample_text): void {
b.bytes = text.data.length;
for _ in 0..b.rounds {
val doc := json::parse(text.data.span) else (_) { return; };
_ = keep(&doc);
}
}
# Work that uses up its input: each round sorts a vector shuffled before the clock
# started.
@bench def sorts_10000(b: &mut bencher): void {
b.batched(def() => shuffled(10000), def(v: &mut vector<u64>) { v.sort(); });
}
# One generic benchmark, measured at two types.
@bench const fills_u8 := fills::<u8>;
@bench const fills_u64 := fills::<u64>;
def main(args: span<strview>): void {
exit(bencher::run(args));
}
```
Built and run:
```
sakura build -O2 --std std -o bench.exe bench/*.sakura
bench.exe --only json --save before.json
... a change ...
bench.exe --only json --compare before.json
```
The report would read like this. The numbers are only for illustration:
```
windows-x86_64, native: 51 samples of at least 1 ms each
[ BENCH ] hashes_words 0.673 ns ±0.2%
[ BENCH ] parses_json 1.21 ms ±0.4% 412 MB/s
[ BENCH ] sorts_10000 402 µs ±0.9%
[ BENCH ] fills_u8 2.10 µs ±0.3%
```
And compared:
```
parses_json 1.21 ms -> 1.09 ms -9.9% faster
sorts_10000 402 µs -> 405 µs +0.7% same
```
## How each part works
- **Calibrating:**
- The benchmark runs with 1 round, then 2, 4 and so on, until one run takes at least
the sample time, 1 ms by default. That's ten thousand of Windows' clock steps, so
the step is under 0.01% of a sample.
- Calibrating also warms the caches, and lets the code page in.
- One slow run stops the doubling early, as the Linux probe found once. So the rounds
found are run once more, and doubled on while that run is under the sample time.
- The probe took 2–3 ms for each benchmark.
- **Sampling:**
- The rounds found are run 51 times. Each run is one sample: its time divided by its
rounds.
- An odd count makes the median one of the samples.
- The probe took 60–90 ms for each benchmark, so a hundred benchmarks take about ten
seconds.
- **The report:**
- **The median,** which an interrupt or a page fault hardly moves.
- **The median absolute deviation,** as a percentage of the median.
- **Not the fastest sample.** The 2026-10-18 report showed it where it was under half
the median, since that meant most samples held a collection. With no collector,
`links_100`'s fastest sample is within 1% of its median, so a wide spread shows in
the deviation alone.
- **A rate,** where `bytes` is set: bytes a round over the median, in MB/s of 10^6
bytes.
- **Times to three figures,** in ns, µs, ms or s. Interpolation writes a real in full,
and `describe` counts whole nanoseconds, so the runner rounds them itself.
- **The header** names the system and the backend, through the `os`, `arch` and
`backend` intrinsics, so a VM's numbers aren't mistaken for an executable's.
- **`batched`:**
- Inputs are made in batches of up to 1,024. Each batch is timed on its own, and the
times are summed, so a batch's inputs needn't all fit in memory at once.
- Each round is one call of `work`, compiled for the lambda given, so at `-O2` it's
inlined. By `tools/function.sakura` on 2026-10-20, such a call costs 0.50 ns in
`-O2` executables, against 2.78 ns for a function value. Work that needs fresh input
usually takes far longer than either.
- **Saving (`--save`):**
- A JSON object, written through `@serial` structs and `json::to_text`, and read back
by `json::from_text`, which the probe did. It holds the header,
then each benchmark's name, rounds, bytes, and every sample, in nanoseconds a round.
- `io::write_file` gives a `result<void, io_error>`. A file that can't be written is
reported, and the status is 1.
- **Comparing (`--compare`, decision 3):**
- For each benchmark in both runs: the old median, the new median, and the change.
- **"faster" or "slower"** only where a Mann–Whitney U test on the two sets of
samples gives p < 0.01, and the medians differ by at least 1%. Otherwise "same".
- The test compares ranks, so it doesn't assume the samples are normal. They
aren't: interrupts and page faults only ever slow a sample down.
- With 51 samples a side, the normal approximation of U is close. It needs only
sorting and a square root.
- **A header that differs,** as a VM against an executable, is said before anything
else.
- **The 1% floor is a guess,** and may be too low: the probe saw code layout alone move
a result by 13% between two builds of the same benchmark. The documentation should
say that a change of a few percent between builds may be layout. Building twice,
with an unrelated change, shows how big that is.
- **Two runs of one build can differ too.** The Linux probe's `links_100` was 4.63–4.73
µs in eight runs and 5.76 µs in two, while each run's samples agreed within 0.6%. The
U test on one run a side would call that a change, so the documentation should say
to compare a few runs a side before believing one.
- **A benchmark's shapes,** checked while compiling:
- `def(b: &mut bencher): void`;
- `def(b: &mut bencher, f: &F): void` or `def(b: &mut bencher, f: &mut F): void`,
where `F` is a `fixture<F>`, lent to every run. Its `setup` takes a tester, which
the runner makes, and where a check fails, the benchmark fails with that check's
message. A fixture taken by value, as a test takes one, is a `compile_error` saying
to take it by reference;
- a constant holding any of these, including a generic instance.
- The runner finds `F` through two overloads of a generic function, one taking
`def(&mut bencher, &F): void` and one `def(&mut bencher, &mut F): void`, since
`type_of` gives the parameter's type only as the reference.
- **`keep` in a benchmark:**
- **Input:** `keep(i)` stops the work from being worked out once, ahead of the loop.
- **Output:** `keep(result)` stops it from being dropped.
- **A reference:** `keep(&buffer)` keeps the writes into a buffer that nothing reads
after.
## Testing
- **The runner, in std's tests** (`test/std/bench.sakura`), written with
`std::testing`:
- **calibration and sampling against a clock the test drives:** the runner reads its
clock through a function value inside, so a fake clock gives fixed times. That
covers doubling, stopping at the sample time, and the count of samples;
- **statistics on fixed samples:**
- the median and the median absolute deviation;
- Mann–Whitney U and its p, against SciPy's `mannwhitneyu`, run once in the
scratchpad. SciPy isn't installed here, so that run installs it;
- **numbers in the report:** three figures, and units changing at 1,000;
- **`--save` read back by `--compare`,** a header that differs, a benchmark in only
one of the two, and a file that can't be written;
- **fixtures:** made once, lent to every run, and closed once, as `&F` and as `&mut F`;
- **`batched`:** each input made once and closed once, outside the time;
- **`--only` and `skip`;**
- **shapes that aren't allowed,** as `compile_error`s, in the analyzer's tests.
- **`keep`, in the compiler's tests:**
- At `-O2`, a loop of `keep(mixed(keep(i)))` still holds its multiplies, by the IR
tests and `--verify`.
- `keep(42)` isn't folded.
- `keep(&buffer)` keeps stores that nothing reads after.
- A corpus program printing values through `keep` gives the same output at every
level, and in the VM.
- **Where they run:** in the VM and as executables at `-O0` and `-O2`, and under
`run --checks`, which stops where an input or fixture is used after it's closed, and
lists the blocks of any never closed. (`SAKURA_COLLECT_ALWAYS=1` went with the
collector.)
## Phases
About 60 lines in the compiler for `keep`, 700 of `std::testing`, and 400 of tests.
1. **`keep`, in the compiler,** with its tests.
2. **The runner:** `@bench`, `bencher`, calibrating, sampling, the report, `--only`,
`--time` and `--samples`. Lent fixtures and constants included.
3. **`batched` and rates.**
4. **`--save` and `--compare`.**
5. **Benchmarks of std,** in a `bench/` directory beside the tests:
- containers, hashing, sorting and formatting;
- JSON and YAML throughput;
- and the compiler's lexer, interner and hash tables, which `docs/performance.md`
names;
- and the probes in `tools/`, `function.sakura`, `iterators.sakura` and
`memory.sakura`, as benchmarks in place of their loops timed by hand.
6. **A "Benchmarks" section in the README.**
## Found along the way
- **std can't write a real to a number of places.** Interpolation writes
`1.4970779418945312`, and `describe` counts whole nanoseconds. The runner rounds
numbers itself, but a formatter in std would serve it, and others. Still so on
2026-10-20: `lpad` and `rpad` pad text, but nothing rounds a real.
- **On Linux, std reads the steady clock by a system call,** about 210 ns a read in
executables, where glibc's `clock_gettime` reads it through the vDSO in 25 ns. A
sample of 1 ms doesn't notice, but code timing short spans by hand does.
## Later, where wanted
- **Allocation counts:** blocks and bytes allocated a round. With no collector, there
are no collections to count or force. This needs a counter in each of the two
runtimes: the native runtime, in `runtime/memory.sakura`, and the VM. Since threads
allocate from caches of their own, each thread counts its own.
- **Timing whole programs:** running a command a number of times and giving the median
of its CPU time, as the optimizer work measured builds. `std::process`'s status would
gain the child's CPU time: `GetProcessTimes` on Windows, and `wait4`'s `rusage` on
Linux, where `sys::wait` already calls `wait4`, asking for none. On Windows, it comes
in 15.625 ms steps.
- **Ratios within a run,** as the probes in `tools/` check theirs: adapters within 10% of
a loop, a `box` within a tenth of `raw_allocate`. A benchmark would name the one it's
measured against, and the report would give the ratio.
- **The steady clock through the vDSO on Linux,** 25 ns a read rather than 210 ns. The
runtime would find it through the auxiliary vector's `AT_SYSINFO_EHDR`, as C libraries
do.
- **Cycles a round,** where the system counts them: `QueryThreadCycleTime`, or Linux's
performance counters.
- **Steadier numbers:** pinning the thread to one core (`SetThreadAffinityMask`,
`sched_setaffinity`), and a higher priority.
- **A failing status for slowing down,** as `--compare FILE --slower 5`, for a check
before merging.
- **The `-O` level in the header,** and whether `run --checks` is checking every access,
neither of which an intrinsic gives yet. `lanes_held()` tells only `-O2` executables
from the rest.
## Decisions for you
1. **Where it lives:**
- **(a) In `std::testing` (recommended).** It shares the walk over attributes,
`--only`, fixtures, and the style of the report. A program importing
`std::testing` gets both.
- **(b) In a module of its own, `std::bench`.** It's separate from tests, but
repeats the walk and the arguments, or the two share code through a third module.
2. **How benchmarks run:**
- **(a) One after another in one program (recommended),** as Go and Criterion run
them.
- There's no copying, and no protocol for handing samples back.
- A benchmark that faults stops the run, with its trace.
- What one benchmark leaves behind can change the next. There's no collector's heap
now, but the blocks it released wait on the free lists, the chunks it opened stay
open, and once any benchmark starts a thread, every allocation after goes
through a thread's cache. `--only` measures one alone.
- **(b) Each in a copy of its own, as tests run.**
- Each starts from the memory the program had before the runner, so the order
doesn't matter, and a fault fails alone.
- But a copy must hand its samples back: through a pipe on Linux, and through a
handle named in the environment on Windows. That isn't probed.
3. **Comparing:**
- **(a) A Mann–Whitney U test on every sample, with a 1% floor (recommended).** This
needs every sample saved, about 1 KB of JSON for each benchmark.
- **(b) Medians only,** where the change is called real when it's over three median
absolute deviations. This is simpler and saves less, but it's worse at telling
noise from a change.
- Either way, each side is one run, and the Linux probe saw two runs of one build
differ by a fifth. `--save` could add a run to its file rather than replace it, so
that `--compare` weighs several.
4. **`keep`'s name and home:**
- **(a) `keep`, in `std::testing` (recommended).** The compiler's corpus has programs
with functions of their own named `keep`, and `std::args` has a private one, so it
isn't put in module `std`, where every program would see it. Programs that
benchmark import `std::testing` anyway.
- **(b) `black_box`, as Rust names it, in module `std`.** No program here uses that
name, and the optimizer's own tests could use it without `std::testing`.
5. **Samples by default:**
- **(a) 51 samples of at least 1 ms (recommended).** That's 60–90 ms a benchmark. On
Windows, the probe's medians repeated within 0.3%. On Linux, within 2.3%, but for
the runs of `links_100` that were off by a fifth as a whole, which more samples in
one run wouldn't fix.
- **(b) A time for each benchmark, as Criterion's 5 seconds,** with as many samples
as fit. That's steadier, but a hundred benchmarks take minutes.