34 KiB
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.
Built in the rebuild alone (roadmap.md, decision 1). Where this plan says both compilers, C's half is left out. What was measured in C stays as measured.
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:
dictagainsthashset, the interner, sorting, andvectorgrowing. The abstraction and optimization work chose between these by timing by hand; - the rebuild's hot spots that
docs/performance.mdnames: hash tables, the lexer's cost a token, and allocation; - the optimizer: whether a pass makes code faster, at each
-Olevel. 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, with both compilers as executables at-O2, the rebuild's at-O0too, and in both VMs; - 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 the rebuild's-O2executables, 58 ns in its-O0ones, and 94 ns in the C compiler's-O2ones. - On Linux,
CLOCK_MONOTONICsteps by 1 ns, but std makes a system call for each read. A read took 211 ns in the rebuild's-O2executables, 293 ns in its-O0ones, and 220 ns in the C compiler's-O2ones. A C program reading the same clock through the vDSO, as glibc does, took 25 ns.
- On Windows, through
-
What the optimizers take 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 C compiler -O2Rebuild -O2Rebuild -O0Empty 0.48 0.24 0.38 A constant in, the result stored to a global 2.28 0.32 3.64 A global read in, the result stored to a global 2.24 0.27 3.70 The counter in, the result discarded 0.48 0.24 3.61 The counter in, the result stored to a global 2.20 1.79 3.65 The counter in, the results summed and printed 2.26 1.96 3.85 In and out through a @foreign defthat gives its argument back, the result stored2.18 1.79 7.75 The same, the result discarded 0.48 0.24 7.32 In and out through relaxed atomics 9.60 1.92 10.65 The work in a function value read from a global, called each round 4.67 3.20 4.88 - The bold rows measured an empty loop. The rebuild moves work on a constant or a global out of the loop, and the C compiler doesn't.
- Both compilers drop a result that nothing reads, even through a
@foreign defwith a body, so going through one hides nothing. - Relaxed atomics keep the work in both compilers. Three a round, a store and a load in and a store out, cost the rebuild 0.1 ns over storing to a global, and the C compiler 7.4 ns.
- 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
@benchfunctions throughdeclarations()andattached, asstd::testingfinds 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 forkeep.-
Medians on Windows, on 2026-10-18, over three runs of each executable and one in each VM:
Benchmark C compiler -O2Rebuild -O2C compiler's VM Rebuild's VM mixes, the work above1.49–1.50 ns 0.672–0.673 ns 19.0 ns 22.8 ns inserts_1000, into a newdict13.2–13.3 µs 4.84–4.85 µs 141 µs 159 µs formats, interpolating two numbers83.1–84.5 ns 54.10–54.12 ns 130 ns 173 ns The median absolute deviation was under 0.5% of the median in the executables, except the C compiler's
mixes, at up to 1.4%. -
Medians on Linux, on 2026-10-20, over three runs of each executable, and eight to ten of
links_100:Benchmark C compiler -O2Rebuild -O2mixes8.17–8.23 ns 1.92–1.93 ns inserts_100055.9–57.2 µs 35.3–36.0 µs formats227–228 ns 172–173 ns links_100, a list of 100boxes made and closed6.01–6.12 µs, and once 7.82 µs 4.63–4.73 µs, and twice 5.76 µs - The median absolute deviation was under 1.4% of the median in the rebuild, and under 2.4% in the C compiler.
- The C compiler's
mixesis mostly the stand-in forkeep: four relaxed atomics a round.
-
Allocation no longer splits the samples. On 2026-10-18,
links_100made a list of 100 references from the collector each round. Its median was six times its fastest sample in the rebuild (3.05 µs and 0.51 µs), and eight times in the C compiler (8.71 µs and 1.07 µs), since most samples held a collection. With no collector, its fastest sample is within 1% of its median in the rebuild, and within 6% in the C compiler. -
A build, or a run, can be off as a whole:
- Code layout alone moved a result by 13%.
inserts_1000took 4.85 µs in one rebuild-O2build on Windows, and 5.47 µs in a build that only added other benchmarks. - On Linux, one executable gave
links_100medians of 4.63–4.73 µs in eight runs and 5.76 µs in two. Each run's own deviation was under 0.6%.
- Code layout alone moved a result by 13%.
-
Calibrating can stop early. In one Linux run,
inserts_1000stopped doubling at 2 rounds, 75 µs a run, where every other run of the rebuild's 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 in both compilers. A closure in a constant, as@bench const inserts_10 := def(b: &mut bencher): void { inserts(b, 10); };, worked in the rebuild, but the C compiler refused it, and still did on 2026-10-20. See "Found along the way".
-
-
Fixtures, on 2026-10-20, in both compilers:
- A fixture that closes, given by value to a benchmark the runner calls many times, is
refused: "
wordsis closed where its scope ends, so it has one owner and is not copied out of the place holding it." A test runs once, sostd::testingcan give its fixture by value. - Lent as
&For&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, takingdef(&mut bencher, &F): voidanddef(&mut bencher, &mut F): void, foundFfrom the benchmark itself. A parameter that isn't a fixture gave the runner'scompile_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 acompile_errorof its own.
- A fixture that closes, given by value to a benchmark the runner calls many times, is
refused: "
-
batchedtaking lambdas, on 2026-10-20: withmakeandworkbounded byinvokable, both compilers tookb.batched(def() => shuffled(10000), def(v: &mut vector<u64>) { v.sort(); }), and inferredTfrom the first lambda. -
Windows' CPU clocks:
GetThreadTimesandGetProcessTimesstep by 15.625 ms, so they can't time a 1 ms sample.QueryThreadCycleTimecounts 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, the same in both trees):- It finds
@testfunctions and constants while compiling, throughdeclarations(),attachedandvalue_of. It tells their shapes apart withif const value_of(d) is def(&mut tester): voidandparams_of, and reports any other withcompile_error. - It runs each test in a copy of the program: forked on Linux, started again with
SAKURA_TEST_ONEon Windows. - It reads
--only TEXTand--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.
- It finds
std::time:instant::now()reads the steady clock:QueryPerformanceCounteron Windows, andclock_gettime(CLOCK_MONOTONIC)by a system call on Linux, not through the vDSO.instant - instantandelapsed()give aduration, which counts whole nanoseconds in ani64. One divided by another is anf64, sotook / nanoseconds(1)is the nanoseconds as a real.describewrites one to two places, as "250ms".
- No CPU clock.
sys::clockreads onlyclock_kind::wallandclock_kind::steady. Nor does std pin a thread to a core: it reads the affinity only to count processors. - Nothing that stops the optimizer. Neither compiler has
keepor anything like it. As the probe found, a loop timed by hand at-O2can 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 --checksknows 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.sakuraandtools/memory.sakuraeach time one loop each way withinstant::now(), keep the work by printing what it gave, and check a ratio: a functor held in afunctioncosts what a function value does; adapters given functors are within 10% offor &x in v; aboxcosts within a tenth ofraw_allocate. Each is built at-O2and run pinned to a core withtaskset;- CPU-time medians of whole builds, and profiles of
build -gcompilers throughtools/profile/; - hand-timed loops in a plan's probe, as the random plan's.
What it needs
- Benchmarks marked and found as tests are, with nothing in the compiler knowing
about them, except
keep. - A way to keep the work being measured from being moved or taken away, at every
-Olevel, that costs nothing itself. - Rounds sized to the clock: enough per sample that Windows' 100 ns clock step, and a clock read of 30–94 ns there and about 210 ns on Linux, don't matter.
- 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.
- 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.
- Rates: bytes a second, where a benchmark says how many bytes a round handles.
- Saving and comparing: whether a change made code faster, slower, or neither, given the noise.
- 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, astester::rundoes. bencheris 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
invokablebounds, so a lambda given tobatchedis 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
&For&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.
keepchanges no value. A program means the same with everykeeptaken out. It only limits what the optimizer may assume.
Layers
The compilers gain keep (decision 4)
#! 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;
- The rebuild:
- A new operation,
keep, incompiler/intermediate/code.sakura, with the traitsop_calls. The passes go by an operation's traits, so none moves it, merges it, or takes it away:dead.sakura,loops.sakuraandsink.sakuraremove or move only loads and whatcode::removableallows, which no call is. Numbering doesn't take its result as its operand, so nothing is folded through it. escapes.sakuraandkeeps.sakuraalready take what an intrinsic is given as kept, sokeep(&buffer)keeps the buffer in memory with nothing added there.emitter/intrinsics.sakuraemits it.- Natively it's a move into a register, which the allocator usually removes. In bytecode it's a move.
- A new operation,
- The C compiler:
INTRINSIC_KEEPinsources/table.hand the intrinsic table inchecker.c.compiler.cemits an instruction thatoptimizer.cdoesn't markpure, and that reads and writes memory, as a call does.machine.candnative.ctreat it as a move.
std::testing gains (decision 1)
#! 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
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.view()) 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 6% of its median, so a wide spread shows in the deviation alone. - A rate, where
bytesis 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
describecounts whole nanoseconds, so the runner rounds them itself. - The header names the system and the backend, through the
os,archandbackendintrinsics, 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-O2it's inlined. Bytools/function.sakuraon 2026-10-20, such a call costs 0.50 ns in the rebuild's-O2executables and 1.78 ns in the C compiler's, against 2.78 ns and 4.80 ns for a function value. Work that needs fresh input usually takes far longer than either.
- Saving (
--save):- A JSON object, written through
@serialstructs andjson::to_text, and read back byjson::from_text, which the probe did in both compilers. It holds the header, then each benchmark's name, rounds, bytes, and every sample, in nanoseconds a round. io::write_filegives aresult<void, io_error>. A file that can't be written is reported, and the status is 1.
- A JSON object, written through
- 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_100was 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): voidordef(b: &mut bencher, f: &mut F): void, whereFis afixture<F>, lent to every run. Itssetuptakes 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 acompile_errorsaying to take it by reference;- a constant holding any of these, including a generic instance.
- The runner finds
Fthrough two overloads of a generic function, one takingdef(&mut bencher, &F): voidand onedef(&mut bencher, &mut F): void, sincetype_ofgives the parameter's type only as the reference.
keepin 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.
- Input:
Testing
- The runner, in each tree's std tests (
tests/std/bench.sakurain the C compiler's tree,test/std/bench.sakurain the rebuild's), written withstd::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;
--saveread 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
&Fand as&mut F; batched: each input made once and closed once, outside the time;--onlyandskip;- shapes that aren't allowed, as
compile_errors, in the analyzer's tests.
keep, in each compiler's tests:- At
-O2, a loop ofkeep(mixed(keep(i)))still holds its multiplies:- in the rebuild, by its IR tests and
--verify; - in the C compiler, in
tests/native.c.
- in the rebuild, by its IR tests and
keep(42)isn't folded.keep(&buffer)keeps stores that nothing reads after.- A corpus program printing values through
keepgives the same output at every level, and in the VM.
- At
- Where they run: both compilers, in the VM and as executables at
-O0and-O2, and underrun --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=1went with the collector.)
Phases
About 60 lines in each compiler for keep, 700 of std::testing, and 400 of tests.
keep, in both compilers, with its tests.- The runner:
@bench,bencher, calibrating, sampling, the report,--only,--timeand--samples. Lent fixtures and constants included. Mirrored in both stds. batchedand rates.--saveand--compare.- Benchmarks of std, in a
bench/directory beside each tree's tests:- containers, hashing, sorting and formatting;
- JSON and YAML throughput;
- and in the rebuild, its lexer, interner and hash tables, which
docs/performance.mdnames; - and the probes in
tools/,function.sakura,iterators.sakuraandmemory.sakura, as benchmarks in place of their loops timed by hand.
- A "Benchmarks" section in the README.
Found along the way
-
The C compiler refuses a closure in a constant whose body calls what can't run while compiling. The rebuild accepts it, and runs it:
def shown(n: u64): void { println($"shown {n}"); } const plain := def(): void { shown(1); }; # C compiler: "Value is not known while compiling. `shown` cannot run while # compiling: it calls `println`, which reads `output_held` ..."Making a closure doesn't run its body, so this looks like a fix to the C compiler. It still held on 2026-10-20, and also where the closure only fills a
dict, which C refuses sincedispose"is a method of a trait that is not aconst def". Until it's fixed, std's own benchmarks write one function a size, since both compilers run them. -
std can't write a real to a number of places. Interpolation writes
1.4970779418945312, anddescribecounts whole nanoseconds. The runner rounds numbers itself, but a formatter in std would serve it, and others. Still so on 2026-10-20:lpadandrpadpad text, but nothing rounds a real. -
Reading the steady clock costs three times as much in the C compiler's executables on Windows (94 ns) as in the rebuild's (30 ns). Both call
QueryPerformanceCounter. Not probed again, as Windows wasn't at hand. On Linux the two cost the same, 220 ns and 211 ns. -
Relaxed atomics cost the C compiler time, and cost the rebuild nothing. On Windows, one round of them cost it 1.3 ns. On Linux, three a round cost it 7.4 ns, and the rebuild 0.1 ns. On x86-64, a relaxed load or store is a plain
mov. -
On Linux, std reads the steady clock by a system call, about 210 ns a read in both compilers' executables, where glibc's
clock_gettimereads 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 four
runtimes: both compilers' native runtimes, in the rebuild's
runtime/memory.sakuraand C'sstd/runtime/memory.sakura, and both VMs. 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:GetProcessTimeson Windows, andwait4'srusageon Linux, wheresys::waitalready callswait4, 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, aboxwithin a tenth ofraw_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
-Olevel in the header, and whetherrun --checksis checking every access, neither of which an intrinsic gives yet.lanes_held()tells only the rebuild's-O2executables from the rest.
Decisions for you
- Where it lives:
- (a) In
std::testing(recommended). It shares the walk over attributes,--only, fixtures, and the style of the report. A program importingstd::testinggets 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.
- (a) In
- 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.
--onlymeasures 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.
- (a) One after another in one program (recommended), as Go and Criterion run
them.
- 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.
--savecould add a run to its file rather than replace it, so that--compareweighs several.
keep's name and home:- (a)
keep, instd::testing(recommended). The rebuild's corpus has programs with functions of their own namedkeep, andstd::argshas a private one, so it isn't put in modulestd, where every program would see it. Programs that benchmark importstd::testinganyway. - (b)
black_box, as Rust names it, in modulestd. No program here uses that name, and the optimizer's own tests could use it withoutstd::testing.
- (a)
- 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% in the rebuild, and within 1.7%
in the C compiler. On Linux, within 2.3% in both, but for the runs of
links_100that 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.
- (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% in the rebuild, and within 1.7%
in the C compiler. On Linux, within 2.3% in both, but for the runs of