Skip to main content

Crate scaling

Crate scaling 

Source
Expand description

A lightweight benchmarking library which:

  • measures until it reaches an accuracy you ask for, and tells you the accuracy it achieved;
  • can measure how a benchmark scales, as a power of its input size;
  • handles benchmarks which must mutate some state;
  • tells you whether two implementations really differ, correcting for how many such questions you asked;
  • lets a whole benchmark suite be declared where it belongs and run from a tiny binary;
  • has a very simple API!

Put an attribute on a function and it is a benchmark. These can live anywhere in your crate, next to the code they measure:

ⓘ
#[scaling::bench]
fn fib_200() -> usize { fib(200) }

#[scaling::bench]
fn fib_500() -> usize { fib(500) }

// A benchmark that mutates state says where the state comes from.
#[scaling::bench(make_input = || vec![0i32; 100])]
fn reverse(xs: &mut Vec<i32>) { xs.reverse() }

#[scaling::bench(make_input = || vec![0i32; 100])]
fn sort(xs: &mut Vec<i32>) { xs.sort() }

The binary that runs them is a main of one call:

// benches/bench.rs, in its entirety
fn main() -> Result<(), scaling::RegistrationError> {
    scaling::Config::default().run_and_print()
}
# Cargo.toml
[dev-dependencies]
scaling = "0.10"

[[bench]]
name = "bench"
harness = false

cargo bench then prints each benchmark as a group of its own, in name order and module-qualified, bench:: here because that is what [[bench]] name = "bench" makes module_path!() at the top of that file:

bench::fib_200  27.99ns ± 0.04ns

bench::fib_500  96.9ns ± 0.2ns

bench::reverse  24.4ns ± 0.2ns

bench::sort  42.2ns ± 0.4ns

The ± figure is the standard error of the reported time, in the same unit as the time itself. Each benchmark keeps sampling until it is small enough (within 1% by default), so cheap-to-measure benchmarks finish quickly and noisy ones keep working until they have earned the precision. Once a long run reports that it has calibrated, Ctrl-C stops it and prints what has been measured so far.

Printing it absolutely rather than as a percentage is deliberate: to decide whether two results really differ you compare the gap between them against the ±, and that is a direct digit-for-digit comparison only when everything is in the same unit.

§Scaling behaviour

#[scaling::bench_scaling] measures how the cost grows with N and reports the constant in front of the law it found, with the same kind of error bar:

ⓘ
#[scaling::bench_scaling(nmin = 0)]
fn fib_scaling(n: usize) -> usize { fib(n) }
bench::fib_scaling  (0.279 ± 0.003)ns/N (R²=1.000)

It works in two stages. The first climbs from small values of N, timing one call at each, until a call is long enough to time properly, and notes how fast cost is growing; those measurements steer and are not part of the answer. The second lays out six log-spaced values of N and times a single call at each, repeatedly, until the answer is precise enough.

Repeating each size is what makes the rest work: every size ends up with an error bar that was measured rather than assumed. That turns “is this the right shape?” into a real test instead of a heuristic. Chi-squared asks whether what the model failed to explain is as small as the error bars say it should be, and a cost that no polynomial describes is rejected outright rather than being fitted anyway.

Measuring stops only when the shape is settled and the constant is precise enough. Both, because a wrong model does not present as an imprecise one - fit a constant to a cost that grows and its prefactor is essentially the mean of every measurement, precise straight away and quite wrong.

The R² figure answers a question the ± cannot. Two things have to be settled - which law, and how big its constant is - and they can fail independently. R² is set to zero outright when the shape was rejected; the ± is the signal for the constant. Crucially, the ± is computed from the sizes and their error bars alone and never sees the timings, so a wrong shape cannot hide inside a wider error bar - it has nowhere to go but the R². A tight ± next to R²=0.000 means “precise about a shape I could not pin down”, and deserves suspicion rather than trust.

Only power laws are fitted. A cost that is not one - O(N log N), or O(2ᴺ) - is reported as the integer power it most behaves like over the range measured, with R²=0.000 and (limit) to say that nothing described it exactly.

§Running them

Every benchmark declared anywhere in the crate is discovered, measured together with the default accuracy and budget, and printed as a table - that is what Config::default().run_and_print() above gives you. The default run needs no configuration to build, no list to add to and no printing to write.

Choosing a tighter accuracy target or time budget means building the Config by hand, still in your own main:

use scaling::Config;

fn main() -> Result<(), scaling::RegistrationError> {
    Config::default()
        .with_max_time(std::time::Duration::from_secs(1))
        .run_and_print()
}

To measure only part of what is registered, give the Config filters. Each takes a function from a name to whether to keep what it names: filter_groups is asked of a group, filter_candidates of a candidate and filter_inputs of an input, and asking twice narrows further.

use scaling::Config;

fn main() -> Result<(), scaling::RegistrationError> {
    Config::default()
        .filter_groups(|group| group.contains("sort"))
        .filter_inputs(|input| input != "huge")
        .run_and_print()
}

What is left is measured, and named, as it would have been in a full run. A benchmark that stands alone is a group of its own, with one candidate named the same, and the implicit input every group has when it declares none, whose name is empty: so the three filters are all asked of it. A group’s baseline is what the others are compared with, so it is kept whenever any other candidate of its group is, whatever the candidate filter says of it. The multiple-comparison correction is for the comparisons the run holds, so a comparison filtered down to on its own is judged more leniently than among the others.

config.run() hands back a Report instead of printing, for a script that wants to look at the numbers rather than show them. Nobody wrote the names down: a standalone benchmark is named for its module and function, and a candidate of a group group:candidate@input. A shorter name will do wherever it fits only one.

use scaling::Config;

#[scaling::bench]
fn sum() -> u64 {
    (0..100u64).sum()
}

let report = Config::default().run().expect("registrations compose");
let timing = report.timing("sum").expect("it ran");
println!("{:.0} ns per call", timing.ns_per_iter);

For custom output, Report::groups() gives each logical group as a Group, in name order. A Group prints itself as a table, and println!("{report}") prints every group, so choosing the order, or printing only some, is ordinary code:

use scaling::Config;

let report = Config::default().run().expect("registrations compose");
let mut groups: Vec<_> = report.groups().collect();
// Put the group called "summing" first, then the rest as they come.
groups.sort_by_key(|(name, _)| *name != "summing");
for (_, group) in groups {
    println!("{group}");
}

What a Group holds is not exposed, so how it is laid out can change; the numbers themselves are reachable by name, as above.

§Comparisons

group makes a function one candidate of a comparison — a bare group = "name" for one group, or group("a", "b") to belong to several at once without those groups being compared with each other. baseline says which candidate the others are reported against; with none marked, the first by name is used, and the report says which it was. If several copies of a crate register the same candidate and each marks it baseline, the oldest copy is the baseline (see “Comparing against your own history” in the crate docs).

#[scaling::input(group = "sorting")]
fn sorting_data() -> Vec<u64> { (0..400).rev().collect() }

#[scaling::bench(group = "sorting", baseline)]
fn stable(v: &mut Vec<u64>) { v.sort() }

#[scaling::bench(group = "sorting")]
fn unstable(v: &mut Vec<u64>) { v.sort_unstable() }

All the candidates are measured in one interleaved round on the same generated input, which is what lets the difference between them be reported with its own error bar rather than by subtracting two independent numbers. To give every candidate the same values the input is generated for each iteration and cloned for each candidate, so its type must be Clone; the generating and cloning are not timed, but they are paid for out of max_time. Candidates are timed for about as long as each other, so a quick one makes more calls than a slow one and takes more of the round’s inputs: where the cost depends on the input, the part of it they do not share is not cancelled from their difference, but left in the error bar.

Most of a comparison’s candidates are not always of interest. When what is wanted is whether this release differs from the last, comparing it with HashSet too only needs to say roughly how much faster it is. Mark such a candidate uninteresting: it is shown as a size, with no verdict, is measured only to Config::with_rough_error (10% by default), and is left out of the count the multiple-comparison correction is made over. Every candidate that is counted makes the others harder to call a change, and a measurement lasts as long as its strictest comparison.

That makes a quick candidate on a large input expensive: a timed stretch of a millisecond may need hundreds of thousands of inputs, since every call is given a new one. An input declared reusable, because one value is as good as another, lets candidates that leave it as they found it (those that take &I, and those that take &mut I and say restores_input) go round a small pool instead. It takes all of a group’s candidates: if one may change its input, every candidate is given new inputs and a warning says so, since a candidate timed warm against one timed cold would measure that difference and not the functions’. A pool is gone round often enough for a processor to learn it, and stays in cache when it is small, so do not declare an input reusable when the function’s speed depends on it being new, as branchy code on random data does. When the input is large, and the pool and everything else would take too much memory, the timed stretch is made shorter instead; installing Allocator lets scaling see how much the inputs really take, and otherwise it estimates. Without it, what a sample touches is still limited, by what its calls and its preparation can touch in their time, and what is not seen is memory reserved and never touched.

The same limit shortens the timed stretch below a millisecond when inputs are slow to make next to a call: an input that takes 10µs to make, and a call of 10ns, are timed in stretches of a few hundred nanoseconds. The warm-up then absorbs less of what the neighbours left behind, and nothing in the output says that it happened. A reusable input that every candidate leaves as it found it avoids it.

Candidates and inputs are registered independently and neither names the other - a candidate says what type it takes, an input says what type it makes, and every pairing sharing a group and a type is measured, with no list of the pairings anywhere. That is what lets one input feed several candidates, and one candidate be compared against several others, just by adding declarations:

#[scaling::bench(group = "sorting", baseline)]
fn stable(v: &mut Vec<u64>) { v.sort() }

#[scaling::bench(group = "sorting")]
fn unstable(v: &mut Vec<u64>) { v.sort_unstable() }

#[scaling::input(group = "sorting", name = "sorted")]
fn already_sorted() -> Vec<u64> { (0..400).collect() }

#[scaling::input(group = "sorting", name = "reversed")]
fn reversed() -> Vec<u64> { (0..400).rev().collect() }

Four declarations, four cells; a third input would make six without touching anything already written. One group can hold several unrelated type families, since candidates are paired only with inputs of their own type - a String candidate is never handed a Vec<u8>; if a group’s candidates disagree on type, it simply splits into one comparison per type rather than refusing to run. Each input’s cells are a comparison; sharing a group with more than one input, they print together as a grid:

sorting (Vec<u64>)  baseline: stable
candidate      reversed           sorted
stable      274ns ± 6ns  351.4ns ± 0.9ns
unstable   -4.0% ± 0.4%     -7.3% ± 0.3%

A group with just one input - the common case, and the only shape a plain group = "..." with no #[input] at all ever has - prints as an ordinary comparison instead, with no grid to read.

§Metrics

A timing is not always the whole story about a candidate. A serializer is also judged by how many bytes it wrote, and a compressor by what it saved. #[scaling::metrics] computes extra numbers from what the candidates of a group returned, and they are printed beside the time. This is the short tour; [#[scaling::metrics]] is the reference for everything it accepts:

use scaling::Metrics;

#[scaling::input(group = "encode")]
fn text() -> String { "abcd".repeat(100) }

#[scaling::bench(group = "encode", baseline)]
fn plain(s: &mut String) -> Vec<u8> { s.clone().into_bytes() }

#[scaling::bench(group = "encode")]
fn doubled(s: &mut String) -> Vec<u8> {
    let mut bytes = s.clone().into_bytes();
    bytes.extend_from_slice(s.as_bytes());
    bytes
}

#[scaling::metrics(group = "encode")]
fn sizes(out: Vec<u8>) -> Metrics {
    Metrics::new().bytes("size", out.len())
}

sizes names a group and takes a Vec<u8>, so it applies to every candidate of encode that returns one - and to candidates added later, without editing it. It takes the output by value, so it needs no Clone and may reuse the buffer. A metrics function that also wants the input, as it was before the candidate ran, takes it first as &I: fn ratio(input: &String, out: Vec<u8>) -> Metrics.

Each candidate is run once more after the timing is done, outside it, and its output is handed over, so a metric is the number from one run: suited to things that do not vary from run to run, such as a size. A group has one metrics function for each type its candidates return; a second for the same type is reported as a contradiction. A candidate that returns another type, or one that cannot be named in a registration (impl Trait, a borrow, or a generic parameter), is measured as usual and has no metrics. Build the numbers with Metrics::bytes, count, ratio and percent, which say what a bare number is counted in, or with Metrics::add, which takes any integer, float or Duration, or a MetricValue made with its own constructors. A metric that is not defined is simply not added, and shows as - in the table.

§Counting allocations

How much memory a candidate used is not in what it returned. Install the counting allocator, mark the metrics function allocation, and ask for the numbers you want to see:

ⓘ
#[global_allocator]
static ALLOC: scaling::Allocator = scaling::Allocator::new();

#[scaling::metrics(group = "encode", allocation)]
fn sizes(out: Vec<u8>) -> scaling::Metrics {
    scaling::Metrics::new()
        .bytes("size", out.len())
        .peak_allocated_bytes()  // the most it held at once: `alloc peak`
        .allocation_count()      // how many times it asked for memory: `alloc count`
        .total_allocated_bytes() // how much it asked for in all: `alloc total`
        .net_allocated_bytes()   // held at the end, net of what it freed: `alloc net`
}

A function can also read the numbers itself, to build a metric of its own from them, with Metrics::allocations():

ⓘ
#[scaling::metrics(group = "encode", allocation)]
fn overhead(out: Vec<u8>) -> scaling::Metrics {
    let held = scaling::Metrics::allocations().map_or(0, |a| a.net_allocated_bytes);
    scaling::Metrics::new().ratio("held per byte", held as f64 / out.len() as f64)
}

It returns None in a function that is not marked allocation, since its run was not counted, and Metrics::allocator_installed() says whether the allocator is in use.

Only the candidate’s own call is counted: not its input, which it was handed, and not what sizes does with the output. A program that asks for counts without installing the allocator is refused before anything runs, rather than shown zeros; asking for them without allocation in the attribute fails with a message saying so. The counters are per thread, so a candidate that hands its work to other threads is counted only for what it does itself, and since the allocator counts everything once it is installed, it slows allocation-heavy code a little - the baseline included.

A group with metrics prints them beside the time, and under it when there are several inputs and one or two metrics:

encode@text (String)  baseline: plain
candidate              time          size
plain      26.56ns ± 0.12ns          400B
doubled      +179.6% ± 1.0%  800B (+100%)

§Why measuring them together matters

Benchmarks run one after another are measured in different machines: the first on a cold package, the fiftieth on a warm one. Their numbers are not comparable with each other, nor with the same suite run tomorrow.

A suite measures them interleaved instead — one round each, in rotation — so every benchmark’s samples spread across the whole session and all of them average the same drift.

It is also what makes the multiple-comparison correction right. Run five comparisons and you have five chances at a false positive; the threshold each one is judged at comes from how many the run actually holds, which is knowable only once they have all been collected. (So a run holding a single comparison judges it more leniently — correctly, but it does mean a small run and a full one are not quite asking the same question.)

What this buys is a bound, not an improvement. Eight identical workloads, measured at the default accuracy on a laptop that was not quiesced, read a median of 1.3% apart within one interleaved suite and 1.5% apart when measured one after another, over 126 runs of each in 21 sessions: where nothing drifts, a wash. The difference is the worst case. In three of the sequential runs identical workloads read 67%, 88% and 132% apart, because the machine slowed down while they were being measured one at a time. No interleaved run was more than 3.1% apart, and the 25 that happened while the machine ran slower than usual were within 0.6%, since a slowdown reaches every benchmark in a suite alike.

So it will not make any single benchmark more reproducible — it averages drift in rather than out — and a suite’s numbers are not comparable with the same benchmark measured on its own. What it gives you is that the numbers within one suite, and across runs of it, were measured in the same machine.

Each benchmark still gets the full time budget of its own, so a suite of n may take n times as long as one benchmark.

That budget is wall-clock time, and building inputs counts against it: make_input, #[input] functions, and the clones each candidate is handed. An input that is expensive next to the function it feeds leaves fewer samples, and so a wider ±. If that happens, raise max_time.

§Very fast functions, and where the code sits

For a function that takes a few nanoseconds, where its code lands in memory is part of what is measured. The same source compiled into two places can run tens of percent apart, and scaling reports that faithfully, with a small ±, because it is real in that binary. It is not noise that more sampling averages away, and it is not a difference in your code: it stays put for a given build and changes when the program is rebuilt. It matters most when comparing two versions of one function, such as a release against the next, where a gap of tens of percent can come from placement alone.

Aligning every function to a cache line removes most of it. Put this in .cargo/config.toml:

[build]
rustflags = ["-C", "llvm-args=-align-all-functions=6"]

In one test, on a quiet machine, 432 comparisons of a function against a copy of itself built from identical source as a separate crate (functions from 5ns to several microseconds, in a real benchmark suite), 105 were reported as changed, 48 of them by 10% or more and the largest by 99%; with this setting 9 were, none by 10% or more and the largest by 8%. Two candidates calling the same function in one crate were not told apart in either build.

It applies to everything the build compiles, and makes the code a little larger. It is an LLVM option, not part of Rust’s stable interface, so its name could change, and it leaves a few percent of placement effects behind, about 8% between separately built copies in that test. Before trusting a small difference between two versions, measure the old one against a second copy of itself, built the same way: if that shows a gap as large as the one you are looking at, the code did not change.

§Quiescing the machine (Linux)

The ± figure covers noise scaling can see while sampling. It cannot see the machine around it — another process sharing your core, the CPU dropping out of turbo as it warms up, an interrupt landing mid-sample. Those shift the answer without widening the error bar.

This crate ships a quiet-bench binary that sets a machine up for benchmarking:

sudo `which quiet-bench` reserve 2

(cargo install puts the binary on your PATH but not on root’s, so a plain sudo quiet-bench usually fails with “command not found”. Copy it to /usr/local/bin if you would rather type the short form.)

That reserves CPU 2: it moves every other process and (where the kernel allows) every interrupt off it, offlines its SMT sibling, disables turbo, pins the minimum frequency to 100%, switches to the performance governor, and disables ASLR. Then run your benchmarks through it:

quiet-bench run cargo test --release

Benchmarks built against scaling pin themselves to the reserved CPUs automatically when a run starts, without any code change: the reservation quiet-bench reserve leaves is enough. quiet-bench run also pins the command before it starts, which matters for programs that know nothing about scaling. Set SCALING_NO_PIN=1 to opt out.

quiet-bench status reports whether a reservation is in effect and whether that process is on it; scaling::quiet::status() does the same from inside a benchmark. When you’re done:

sudo `which quiet-bench` restore

Everything here is Linux-only and entirely optional; on other platforms, and when no reservation is active, benchmarks simply run normally.

§License

Licensed under either of

at your option.

§Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

§Attribute inputs and setup

A flat benchmark may take no argument or one input. Use input = value when each iteration should receive a clone of the same initial value, or make_input = || value when each iteration needs a newly built value. The function may take &I, &mut I, or I by value; by-value inputs are useful when the benchmark consumes its input:

#[scaling::bench(input = vec![0_u8; 1024])]
fn count(bytes: &[u8]) -> usize { bytes.len() }

#[scaling::bench(make_input = || vec![0_u8; 1024])]
fn consume(bytes: Vec<u8>) -> usize { bytes.len() }

For comparisons, candidates use the group’s shared #[scaling::input] instead of input = or make_input = on the candidate. The shared input is generated a batch to a round, and each call is given a new input of its own, cloned so that every candidate in a round draws from the same batch. That is why the input type must be Clone. An input declared reusable, because one value is as good as another, lets candidates that leave it as they found it go round a small pool instead (see bench), and one declared build_once is built once for each group and need not be Clone (see input). Generating and cloning are never timed, only paid for out of max_time. A setup-once candidate uses the shared input only when its returned closure is first built; later inputs are still generated, but that cached closure is called without them. Comparison candidates must take &I or &mut I; owned inputs are currently supported only by standalone benchmarks.

A function returning impl Fn() -> O or impl FnMut() -> O is a setup-once benchmark: the function runs once, then the returned closure is called for every timed iteration. This is useful when mutable state must persist between calls, such as an advancing random-number generator. With input = value, the value is passed to setup once, not cloned for every call to the returned closure. This form cannot be combined with make_input =, and a returned closure that itself takes an argument is not supported.

For a scaling benchmark, nmin is required and input = is unavailable because the input must vary with n. Use make_input = |n| ... to build size-dependent input; it runs before timing, once per sample. A scaling benchmark can also return impl Fn() -> O or impl FnMut() -> O: setup is then cached separately for each size, and the returned closure is timed at that size. It cannot be combined with make_input =.

An input registration can be expanded across types with types(A, B, ...) or across sizes with sizes(1, 2, ...). A type-expanded input is generic and produces one registration per listed type. A size-expanded input takes the size as its argument and produces one input per listed size. These options are alternatives, not combinable. Candidates can likewise use types(A, B, ...) to register a generic candidate once per listed input type. For example, this registers two inputs for the same comparison:

#[scaling::input(group = "sorting", sizes(8, 32))]
fn values(size: usize) -> Vec<u8> { (0..size as u8).collect() }

#[scaling::bench(group = "sorting")]
fn sort(values: &mut Vec<u8>) { values.sort_unstable() }

§Reading the output

A flat benchmark prints as name value ± error. The ± is the standard error of the value, in the same unit, and the value is printed to the precision that error justifies. Two marks may follow:

  • (limit): the time budget ran out before the accuracy target was met, so the ± is wider than you asked for (Timing::hit_limit).
  • (untrusted): too few samples were taken for the ± itself to mean anything (Timing::untrustworthy).

Both can appear together as (limit, untrusted).

A scaling benchmark prints (constant ± error)ns/N (R²=…). R²=0.000 with (limit) means no power of N described the cost. A longer max_time will not change that, since it is the model, not the sampling, that failed.

In a comparison, the baseline’s row is an absolute time and every other candidate’s is its difference from the baseline: -7.0% ± 0.4% is seven percent faster, give or take the error. (< 1.0%) means no difference was found, and the figure is the smallest change this run could have detected at its accuracy goal.

A group with several inputs prints as a grid, candidates down and inputs across, with the baseline named in its title. The layout is chosen for you: a group that would be wider than 100 columns is turned on its side, and if that is still too wide it is printed with a line to each cell. A group whose inputs differ in type is split into a table to each type when one table will not hold it. Because (limit) and (untrusted) marks widen cells, two groups of the same shape can lay out differently. Nothing about it is configurable yet; a Group prints itself, so a caller can choose which groups to print and in what order (see Report::groups).

A run says how many benchmarks it is about to measure (on stderr) and, once it has gone on for a few seconds, how it is going (see Config::run); the results come only when all of them have finished. The suite is measured interleaved, so there are no partial results before then, unless Ctrl-C stops the run early (see Report::was_interrupted). To measure only some of what is registered, ask the Config: Config::filter_groups, Config::filter_candidates and Config::filter_inputs each take a function from a name to whether to keep it. Leaving a benchmark out of the build altogether is what a feature gate is for (see below). Results are not saved: Report, Timing and Difference deliberately have no serialization, because two runs a day apart were not measured on the same machine. To compare with the past, measure the past in the same run, as below.

§Keeping a src/-resident benchmark out of ordinary builds

Nothing here wraps the function in a #[cfg] for you: a #[cfg] written above the attribute strips the whole item, macro included, before it ever expands. A benchmark placed in benches/ is already fine as it is - cargo only builds that directory for cargo bench - but one placed in src/, to sit next to the code it measures, compiles into every build by default: an ordinary cargo build, and every crate depending on yours. Gate it yourself, one of two ways.

A feature of your own, if you are also going to publish this crate and want cargo bench --features my-benchmarks to keep working the ordinary way. Make scaling an optional dependency tied to that feature, and add it a second time, plainly, as a dev-dependency - so benches/bench.rs itself always has it, feature or not:

[dependencies]
scaling = { version = "...", optional = true }
[dev-dependencies]
scaling = "..."
[features]
my-benchmarks = ["dep:scaling"]

then write every src/-resident benchmark under that same #[cfg]:

#[cfg(feature = "my-benchmarks")]
#[scaling::bench]
fn fib_200() -> usize { fib(200) }

and run with cargo bench --features my-benchmarks. scaling ships no feature of its own for this: a fixed name baked into the macro, say #[cfg(feature = "scaling-bench")], would be a convention nobody asked for, and would compile silently to nothing for a crate that had never defined that exact feature - worse than an explicit gate you chose yourself. The cost of this route is a #[cfg] to remember on every benchmark you write this way.

This route also buys something the other one cannot: benchmarks that cross crate boundaries. #[scaling::bench] in src/ becomes part of the crate’s own compiled output, the same as any other item behind a feature - and registration is collected from everything linked into one binary, regardless of which crate contributed it. So a family of related crates - rand_core, rand_chacha, rand_pcg, and the like - can each register their own benchmarks behind their own feature, and a single downstream binary that depends on several of them with those features enabled gets one combined, interleaved run spanning the whole family, with no crate having to know about any of the others’ benchmarks in advance. This is exactly why every registration carries crate_name/crate_version: two crates - or two versions of one - registering into the same binary is an intended scenario, not an edge case, and a name they happen to share is resolved by keeping every version, told apart by where it came from. #[cfg(test)] code never leaves the crate that defines it, so the dev-only route below cannot do this at all.

Dev-only, no feature at all, if you would rather not annotate every benchmark individually. Put scaling in [dev-dependencies] only - nothing under [dependencies] - and wrap the whole module in #[cfg(test)] instead of one attribute per function:

#[cfg(test)]
mod benches {
    #[scaling::bench]
    fn fib_200() -> usize { super::fib(200) }

    #[test]
    #[ignore] // a real run needs --release; plain `cargo test` should not pay for it
    fn run() {
        scaling::Config::default()
            .run_and_print()
            .expect("the benchmarks are registered consistently");
    }
}

and run with cargo test --release -- --ignored run. An ordinary cargo build never sees #[cfg(test)] code at all, so it never touches scaling, inventory, or anything either depends on - the same zero cost to a normal build the feature route buys, bought instead by #[cfg(test)], something every Rust crate already uses, at the cost of the ordinary cargo bench CLI: #[test] functions are not run by cargo bench on stable Rust, so this route goes through cargo test instead (hence --release, since cargo test’s own default profile is unoptimised) rather than through a main of your own.

§Comparing against your own history

The same group/baseline machinery any other comparison in this crate uses also answers “did this get slower since the last release” - and more accurately than storing a number from a past run and diffing today’s against it later, because two runs a day apart do not share a machine state: a warmer package, a different mix of interrupts, a CPU that has since settled into a lower clock step, all shift a stored number without shifting today’s result to match. Comparing against your own history this way never stores a number at all - it measures the old code itself, fresh, in the very same interleaved round as the new code, so whatever the machine happens to be doing shifts both equally and cancels out of the difference, exactly as it does for any other pairing here.

Pin the old release as a dev-dependency, under a name of your own that is not the crate’s own:

[dev-dependencies]
my_crate_previous = { package = "my-crate", version = "=1.2.0" }

or, to compare against the tip of your default branch rather than a tagged release, a git dependency naming no branch/tag/rev tracks origin’s HEAD:

[dev-dependencies]
my_crate_previous = { package = "my-crate", git = "https://github.com/you/my-crate" }

or a particular commit, by rev:

[dev-dependencies]
my_crate_previous = { package = "my-crate", git = "https://github.com/you/my-crate", rev = "a1b2c3d" }

The package = ".." rename is what lets a crate depend on an older copy of itself: the old copy gets a name that the crate’s own code does not already use.

Copies of a crate are put in order by version wherever it matters: the older of several that each mark baseline is the baseline, and the newest of several copies of an input is the one used. Versions are compared as three numbers, major.minor.patch, so 0.10.0 is newer than 0.9.0. Anything after a - or + is ignored, so 1.0.0-rc.1 and 1.0.0 are the same version, and a part that is missing or does not parse counts as 0.

Either way, what you get is the actual function definitions of that version, not a cached timing - so write the comparison the ordinary way, the released crate’s public API on one side and your own on the other:

ⓘ
#[scaling::bench(group = "sort", baseline)]
fn released(v: &mut Vec<u64>) { my_crate_previous::sort(v) }

#[scaling::bench(group = "sort")]
fn current(v: &mut Vec<u64>) { my_crate::sort(v) }

baseline names the released version, so the report reads the way a regression check should: the code being written is measured against what already shipped, not the other way around.

Benchmarks the crate registers for itself, behind a feature as above, take part the same way: the copy under my_crate_previous registers them too, and each is reported as name@<version>. Where the copies each mark baseline, the older version is the baseline. A copy at the same version, as the tip of your default branch is until the next release, is told apart by where it came from instead: name@git for a checkout cargo fetched from git, name@registry for one from a registry, and name@local for one in your own tree. Where there are several of a kind, their directories tell them apart: name@6b0b7fb for a git checkout, which cargo names for the revision, and name@my-crate for your own tree, leaving off the folders within a repository that they all end in. Of two copies of one version, the newer is the one cargo was asked to build - the package you ran cargo bench for - and so the older is the baseline. If neither is, the one in your own tree is newer than one cargo fetched, and after that the later directory is. The title of the group’s table names the baseline that was used, as baseline: sum@git.

There is one sharp edge: it stops working if two different versions of scaling itself ever end up anywhere in the dependency graph, since registration is keyed on the literal monomorphized type inventory collects, and two scaling versions split the registry silently rather than erroring.

§Benchmarking algorithm

§Flat benchmarks: #[bench]

An iteration is a single execution of your code. A sample is a measurement, during which your code may be run many times.

A sample is timed in laps of calls, a millisecond or so each: a warm-up lap whose time is thrown away, then a short lap and a long one nine times as long. The warm-up absorbs whatever the sample before it left behind - a cold cache, a vector unit that had gone to sleep - so that what is measured is your code running steadily, whatever ran before it. Reading the clock costs something, and may set off something else; each lap carries it once, so the long lap less the short one, over the difference in their calls, has none of it. A first pass finds how many calls make a lap.

We then take one sample per round, and stop once the standard error of their trimmed mean (a quarter cut from each end, which sheds the occasional interruption) is small enough, and never on fewer than eight. This directly answers “how precisely do I know ns_per_iter”, which is what you actually want.

You may choose how accurate you want your benchmarks to be (see Config) or you may accept a reasonable default. Both a relative and an absolute goal are available, and sampling stops as soon as either is met, so the coarser one governs.

The output includes the standard error of the measurement, printed after the ± in the same unit as the measurement itself, and the measurement is printed to exactly the precision that error justifies. Quick statistics note: in general you should expect a measured value to be more than two standard errors away from the true value about 5% of the time, and about a third of the time you should expect the discrepancy to be more than one standard error. So do not take this ± value as a bound on the error!

Timing::std_error and Timing::rel_std_error give the error absolutely and relatively, Timing::iterations and Timing::samples say how much work it took, Timing::hit_limit tells you if the budget ran out before the target accuracy was met, and Timing::untrustworthy tells you if too few samples were collected for the error bar itself to mean anything. Those are marked (limit) and (untrusted) in the output.

If a benchmark requires some state to run, one copy of the initial state is prepared per iteration, unless the benchmark cannot change it and shares a few instead (see bench).

§Scaling benchmarks: #[bench_scaling]

These work in two stages, and the split is the point of the design.

Stage one picks the sizes. It climbs from nmin, timing a single call at each candidate, until one call is long enough to time properly - below about 20 microseconds you are measuring the clock, not the function. That size becomes the bottom of the ladder, and the growth rate measured along the way says how much a larger size will cost, which is what lets stage two choose a top it can actually afford. These measurements steer and nothing else; none of them ends up in the answer.

Stage two measures. It lays out six log-spaced sizes and times a single call at each, repeating - six times to begin with, more until the answer is precise enough. Repeating is what makes the difference: each size ends up with an error bar that was measured rather than assumed, and that changes what can be asked of the fit.

The range is chosen in time, not in size: far enough up that the largest size takes four times as long as the smallest, which stage one’s growth rate converts into a size range. A fixed size range would mean a different time range for every benchmark, since four times the size is four times the work for a linear cost and sixty-four times for a cubic one. No time budget is consulted - what makes a range good is that it separates the powers while costing little, and stage one already measured both of those. The opening rounds come to about eighty times the cheapest call, so a benchmark sitting on the 20-microsecond floor is measured in under two milliseconds.

Nothing is batched. A benchmark worth asking about the scaling of is one that gets slow as N grows, so where a batch would have been needed to out-measure the clock, a larger N does the same job and tells you something you wanted to know anyway. It also keeps the model honest: timing a batch and dividing by its length turns the fixed per-batch overhead into a c/N term, which no polynomial in N can represent, so it comes out smeared across every coefficient. One call per sample leaves that overhead as a plain constant, which the fit represents exactly.

Two separate things then have to be settled, and the output reports them separately because they fail independently:

  • Which law? With measured error bars this becomes a real goodness-of-fit test rather than a heuristic: chi-squared asks whether what the model failed to explain is as small as the error bars say it should be. A cost that no polynomial describes is rejected outright, and reported with goodness_of_fit zeroed and the (limit) mark, alongside the integer power it most behaves like over the range measured.
  • How big is its constant? ScalingStats::rel_std_error answers this, and it is what the ± in the output shows. Measuring continues until it meets the same accuracy target the flat benchmarks use, so (43.1 ± 1.2)ns/N means the same kind of thing as 43.1ns ± 1.2ns does for a flat one.

The two are deliberately not merged into one number, and measured error bars are what keeps them apart. Where errors are only assumed, the usual move is to widen them by however badly the fit turned out - which quietly converts “wrong shape” into “imprecise constant”, and hides exactly the failure worth knowing about. Here the coefficient errors come from the sizes and their error bars alone and never see the timings, so a bad shape has nowhere to hide but chi-squared. Read the two together, and be suspicious of a small ± sitting next to R²=0.000.

Measuring stops once the model is accepted and its constant meets the accuracy target, or when the time budget runs out - 10 seconds by default, which is a backstop rather than something to be spent. Both conditions are needed, because a wrong model does not present as an imprecise one: fit a constant to a cost that grows and its prefactor is near enough the mean of every measurement, precise immediately and quite wrong.

Only power laws are fitted. A cost that is not one - O(N log N), or O(2ᴺ) - is reported as the integer power it most behaves like over the range measured, with goodness_of_fit zeroed and the (limit) mark to say that nothing described it exactly. Naming those shapes needs a different kind of fit and would be a different feature; measuring a power well is the thing this does. For the same reason, a longer max_time does not rescue a benchmark reported with (limit) and R²=0.000: the sampling was not what failed.

§Caveats

§Caveat 1: Harness overhead

**TL;DR: Compile with --release; the overhead is likely to be within the noise of your benchmark.

Work which scaling does once-per-sample is kept negligible: the flat benchmarks size each batch so that a sample takes far longer than the two Instant::now() calls bracketing it, and the scaling benchmarks choose sizes large enough that a single call dwarfs them. However, work which is done once-per-iteration will be counted in the final times.

  • For a benchmark taking no input this amounts to incrementing the loop counter and passing the return value through std::hint::black_box.
  • For one taking an input, we also do a lookup into a big vector in order to get the input for that iteration.
  • If you compile your program unoptimised, there may be additional overhead.
  • If you install the counting Allocator to report allocations, it counts every allocation, including those made inside timed code, which costs a few instructions each. The baseline pays it too, so a comparison stays fair, but an allocation-heavy benchmark reads a little slower than it would without it.

The cost of the above operations depend on the details of your benchmark; namely: (1) how large is the return value? and (2) does the benchmark evict the input vector from the CPU cache? In practice, these criteria are only satisfied by longer-running benchmarks, making these effects hard to measure.

§Caveat 2: Pure functions

TL;DR: Return enough information to prevent the optimiser from eliminating code from your benchmark.

Benchmarking pure functions involves a nasty gotcha which users should be aware of. Consider the following benchmarks:

#[scaling::bench]
fn fib_1() -> usize { fib(500) }                      // fine

#[scaling::bench]
fn fib_2() { fib(500); }                              // spoiler: NOT fine

#[scaling::bench(make_input = || 0usize)]
fn fib_3(x: &mut usize) { *x = fib(500); }            // also fine, but ugly

The results are a little surprising:

fib_1:   262.759ns ± 0.079ns
fib_2:   0.59300ns ± 0.00075ns
fib_3:   262.805ns ± 0.025ns

Oh, fib_2, why do you lie? The answer is: fib(500) is pure, and its return value is immediately thrown away, so the optimiser deletes the call entirely. What is left to measure is an empty loop, which clocks in at a fraction of a nanosecond - not the 258 ns the work would have cost.

What about the other two? fib_1 looks very similar, with one exception: the closure which we’re benchmarking returns the result of the fib(500) call. When it runs your code, scaling passes that return value through std::hint::black_box, which the optimiser must treat as though it were used, before throwing it away. This is why fib_1 is safe from having code accidentally eliminated.

In the case of fib_3, we actually do use the return value: each iteration we take the result of fib(500) and store it in the iteration’s own input. This has the desired effect, but looks a bit weird.

This applies equally to bench_scaling and to a comparison’s alternatives, not just to a plain #[bench]: every timed call, whichever of the three it is, is protected by std::hint::black_box the same way. (A plain #[bench] runs as a comparison of one alternative, so those two share their timing loop.) A scaling benchmark has one further wrinkle: the size N itself is also passed through black_box before the call, not just the result afterward - without that, the optimiser can see N as a literal within one round and hoist the call out on that basis alone, the same elimination this caveat is about, one step earlier.

§Caveat 3: A busy machine

TL;DR: on Linux, sudo `which quiet-bench` reserve 2 then quiet-bench run <your benchmark>.

The accuracy scaling reports covers noise it can see while sampling. It cannot see the machine around it: another process on the same core, a CPU dropping out of turbo as it heats up, or an interrupt landing mid-sample all shift the answer without widening the error bar.

The quiet-bench binary shipped with this crate reserves one or more CPUs for benchmarking and moves everything else - processes, interrupts - off them, and pins the clock frequency. Benchmarks then pin themselves to the reserved CPUs automatically, with no code change. See the quiet module for the details, and quiet::status to check at runtime whether it took effect.

§CI

quiet-bench reserve wants root and exclusive cores, which an ordinary CI runner - shared, often virtualized, rarely handing out either - usually cannot give it. quiet::status still tells you outright rather than letting a run silently assume it is quiesced: check it in CI the same way you would locally, and expect quiet::Status::NotQuiesced there.

Be honest with yourself about what a tight error bar is worth on a busy machine: the statistics can catch too few samples, a fact about the budget they can see. They cannot catch a busy machine, which is exactly the failure this caveat opened with - the whole run shifted together, so the error bar stays tight and looks fully earned. There is no flag that turns that into a caught case; the only fix is a quieter machine, or judging results from CI with that firmly in mind rather than trusting them the way a quiesced run’s would be trusted. [#[scaling::metrics]]: macro@metrics

Modules§

quiet
Detecting and honouring a quiesced benchmarking environment.

Structs§

Allocations
What a candidate allocated during its call: what Metrics::allocations returns, and what the allocation metrics show.
Allocator
A global allocator that counts what a benchmark allocates, and otherwise leaves everything to the system’s.
Config
How hard a benchmark works to pin down ns_per_iter, and when it gives up.
Difference
The measured difference between a timing and its baseline.
Group
The results of one logical group: its candidates measured on its inputs.
MetricValue
One number about a cell, together with what it is counted in.
Metrics
A record of named numbers about one cell - one candidate on one input - built a field at a time. It is what a metrics function returns, and the crate docs for that attribute say what happens to it next.
NameError
Why a Report could not give what was asked for by name.
RegistrationError
Why Config::run measured nothing: what is registered cannot be run as written. Two benchmarks may share a name, a group may have two baselines, or a metrics function may count allocations in a program that has not installed Allocator.
Report
What a run measured, reached by name.
Scaling
The timing and scaling results (without statistics) for a benchmark.
ScalingStats
Statistics for a benchmark run determining the scaling of a function.
Timing
A benchmark’s measured timing.
Timings
A comparison’s results: a Timing for each candidate, baseline first.

Attribute Macros§

bench
Registers a function as a benchmark, or as a candidate in a comparison.
bench_scaling
Registers a function as a scaling benchmark, measured at several sizes to find how its cost grows as a power of N.
input
Registers an input, shared by every candidate of its group that takes its type.
metrics
Computes extra numbers from what the candidates of a group returned, so that they are shown beside the times: how many bytes a serializer wrote, how well its output compresses, how much memory it held.