Skip to content
systemcoding.dev
Performance

Benchmark Rust Code Reliably With Criterion

Set up Criterion 0.5 in Rust 1.83, write a bench_function with black_box, run cargo bench and read the time estimate, outliers and change detection.

7 min read
Summarize in AI
Flat illustration of a rising bar chart and a gauge, with the Rust, LLVM and Linux logos.

Rust ships with a #[bench] attribute, but it works only on the nightly compiler and has never been stabilized. For stable Rust, the standard answer is Criterion, a statistics-driven benchmarking crate. It warms the code up, collects many samples, estimates the time with a confidence interval, flags outliers, and on the next run compares against the saved results to say whether performance changed. This post sets up Criterion 0.5 in a crate built with Rust 1.83, writes a first benchmark of two ways to sum a vector, reads the report and explains the knobs that matter. The same principles as in the guide to benchmarking native code apply, and Criterion automates most of them.

Set up the crate

Create a library crate and add Criterion as a development dependency. Benchmarks live in a benches directory, and each benchmark file needs harness = false because Criterion supplies its own main instead of the default test harness:

Cargo.tomlTOML
[package]
name = "sums"
version = "0.1.0"
edition = "2021"

[dev-dependencies]
criterion = "0.5"

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

The library holds the two functions under test. One uses an indexed loop and one uses the iterator sum:

src/lib.rsrust
pub fn sum_loop(data: &[u64]) -> u64 {
    let mut total = 0u64;
    for i in 0..data.len() {
        total = total.wrapping_add(data[i]);
    }
    total
}

pub fn sum_iter(data: &[u64]) -> u64 {
    data.iter().fold(0u64, |acc, &x| acc.wrapping_add(x))
}

Both use wrapping_add so they behave identically in debug and release builds. Without it, an overflow would panic in debug mode and wrap in release mode, and the two functions would differ in behavior on large inputs.

Write the benchmark

A Criterion benchmark is a function that takes &mut Criterion and registers one or more named measurements. Group registration and main are generated by two macros:

benches/sum_bench.rsrust
use criterion::{criterion_group, criterion_main, Criterion};
use std::hint::black_box;
use sums::{sum_iter, sum_loop};

fn bench_sums(c: &mut Criterion) {
    let data: Vec<u64> = (0..100_000u64).collect();

    c.bench_function("sum_loop 100k", |b| {
        b.iter(|| sum_loop(black_box(&data)))
    });

    c.bench_function("sum_iter 100k", |b| {
        b.iter(|| sum_iter(black_box(&data)))
    });
}

criterion_group!(benches, bench_sums);
criterion_main!(benches);

The shape is: build the input once outside the closure, then call b.iter with a closure that runs the code being measured. b.iter repeats the closure in a timed loop and returns the closure's result so that Criterion can drop it. std::hint::black_box wraps the input so the compiler cannot assume what is in the slice and fold the computation away at compile time. It has been stable since Rust 1.66 and is the right choice over older workarounds, and the next post on black_box goes deeper into what it guarantees.

Run it

Shell
cargo bench

Cargo builds the benchmark with the bench profile, which inherits from release, so it is optimized. Criterion prints a report for each benchmark:

Text
sum_loop 100k           time:   [20.512 µs 20.598 µs 20.689 µs]
Found 6 outliers among 100 measurements (6.00%)
  4 (4.00%) high mild
  2 (2.00%) high severe

sum_iter 100k           time:   [20.341 µs 20.424 µs 20.517 µs]
Found 3 outliers among 100 measurements (3.00%)
  3 (3.00%) high mild

The times are illustrative. The three numbers inside the brackets are the lower bound, the point estimate and the upper bound of a 95 percent confidence interval for the mean time per iteration. A narrow interval means a stable measurement. The two intervals here overlap almost entirely, which tells you the two implementations perform the same within the noise. That is the honest reading: with the interval overlapping, you cannot claim one is faster. This is the kind of result that a single timing would have turned into a false story.

The outlier lines report how many of the 100 samples were far from the rest. A few high outliers are normal: an interrupt or a context switch makes one sample slow. A large share, over ten percent, says the machine is noisy and the result is suspect.

What Criterion does for you

Criterion first runs the function for a warm-up period, 3 seconds by default, so caches and branch predictors settle and the CPU reaches steady frequency. It then decides how many iterations to put in each sample so the measurement runs for the target time, 5 seconds by default, collects 100 samples and fits a linear regression of time against iteration count to estimate the per-iteration time. The regression approach removes a fixed overhead per sample, such as the cost of reading the clock, which a plain mean would include.

On later runs, Criterion keeps the previous results in target/criterion and compares. If you change an implementation and rerun, you get a change report:

Text
sum_loop 100k           time:   [12.311 µs 12.354 µs 12.401 µs]
                        change: [-40.322% -40.058% -39.790%] (p = 0.00 < 0.05)
                        Performance has improved.

The change line gives a confidence interval for the relative change and a p-value from a significance test. Criterion reports "Performance has improved" or "regressed" only when the change is statistically significant at the threshold; otherwise it says "No change in performance detected" or "Change within noise threshold". It also writes an HTML report to target/criterion/report/index.html with plots of the sample distribution, if you have gnuplot installed or when it uses its built-in plotters.

Benchmark across input sizes

A single size can mislead, since cache effects change with the data. Criterion's benchmark groups let you sweep sizes and see how time grows. Register a group and loop over the sizes with BenchmarkId:

benches/sizes.rsrust
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion, Throughput};
use std::hint::black_box;
use sums::sum_iter;

fn bench_sizes(c: &mut Criterion) {
    let mut group = c.benchmark_group("sum_iter");
    for size in [1_000usize, 10_000, 100_000, 1_000_000] {
        let data: Vec<u64> = (0..size as u64).collect();
        group.throughput(Throughput::Elements(size as u64));
        group.bench_with_input(BenchmarkId::from_parameter(size), &data, |b, d| {
            b.iter(|| sum_iter(black_box(d)))
        });
    }
    group.finish();
}

criterion_group!(benches, bench_sizes);
criterion_main!(benches);

Add [[bench]] name = "sizes" with harness = false to Cargo.toml as well. Setting Throughput::Elements makes Criterion report elements per second in addition to time, which is the figure to compare across sizes: a drop in elements per second as the size crosses the L2 or L3 capacity shows the memory hierarchy at work.

Tune the run

Defaults suit most cases, and you change them in the group or on the Criterion value. sample_size(n) sets the number of samples (at least 10), measurement_time the target measurement time, and warm_up_time the warm-up. A slow benchmark that takes a second per iteration needs a lower sample size and a longer measurement time, or Criterion warns that it cannot collect all samples in the time:

rust
let mut group = c.benchmark_group("slow");
group.sample_size(10);
group.measurement_time(std::time::Duration::from_secs(20));

You can also name a baseline to compare against, with cargo bench -- --save-baseline before before a change and cargo bench -- --baseline before afterward, which survives other runs in between.

Compare two implementations in one group

When you compare alternatives, put them in one benchmark group so the report and the plots line up. Criterion's bench_with_input and BenchmarkId give each implementation a name and a parameter, and the HTML report draws them side by side with a violin plot:

benches/compare.rsrust
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion};
use std::hint::black_box;
use sums::{sum_iter, sum_loop};

fn bench_compare(c: &mut Criterion) {
    let mut group = c.benchmark_group("sum");
    for size in [1_000usize, 100_000] {
        let data: Vec<u64> = (0..size as u64).collect();
        group.bench_with_input(BenchmarkId::new("loop", size), &data, |b, d| {
            b.iter(|| sum_loop(black_box(d)))
        });
        group.bench_with_input(BenchmarkId::new("iter", size), &data, |b, d| {
            b.iter(|| sum_iter(black_box(d)))
        });
    }
    group.finish();
}

criterion_group!(benches, bench_compare);
criterion_main!(benches);

Each result is named like sum/loop/1000, so you can filter with cargo bench -- sum/iter. The group summary plot in the HTML report places the two lines on one axis, which is the quickest way to see whether the implementations cross over at some size.

Limits of Criterion

Criterion measures the mean time per iteration with a regression, which is excellent for operations that take microseconds and above. For operations in the single-digit nanoseconds, the measurement is dominated by the loop and the barrier, and you should treat differences of a nanosecond with suspicion. It also reports one aggregate and not the latency distribution of individual calls, so it cannot tell you about tail latency. For that you need a harness that records each call's time in a histogram. And it runs on a quiet machine only as well as the machine is quiet: its statistics describe the samples it took, not the noise of the room around them.

Share

Keep reading

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

Spinlocks vs Mutexes: When Spinning Wins

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

6 min read

Get new posts by email

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

Unsubscribe in one click. No spam, ever.