Sub topic 1
Why benchmark, and why Criterion
What this chapter covers
This chapter explains why performance claims need measurements. It shows why a quick timing with std::time::Instant is not enough, and it describes what Criterion.rs adds. Later chapters cover project setup, writing benchmarks, and reading results. Here you build the reasoning that makes those steps worth doing.
Prerequisites
This chapter assumes you can do the following:
- Read and write basic Rust: functions, closures,
match, and iterators. - Use Cargo to build, run, and test a project, and know what
--releasedoes. - Edit
Cargo.toml, including the[dev-dependencies]section. - Explain in general terms what runtime and performance mean. You do not need profiling experience.
You do not need to know any statistics. The chapters that use statistical ideas explain them as they come up.
Why benchmark at all
Programmers are often wrong about where time goes. A function that looks expensive may be cheap because the compiler inlines it or the data fits in cache. A function that looks trivial may be slow because it allocates on every call. Reading code gives you a hypothesis about performance. Only a measurement can confirm it.
Benchmarking is useful for four jobs:
- Choosing between implementations. Should you use a
Vecor aHashMapfor 20 items? Should you sort first and binary search, or scan linearly? The answer depends on the input size and the hardware, so you measure. - Checking an optimization. An edit that "should" be faster sometimes makes no difference or makes things worse. A before-and-after comparison tells you which.
- Catching regressions. Performance often degrades gradually, through small changes that each look harmless. A saved benchmark result gives you a reference point to compare against.
- Setting expectations. Knowing that a parser handles roughly a given number of megabytes per second tells you whether it can sit in a request path or needs to run in the background.
Benchmarking is not the same as profiling. A benchmark answers "how long does this code take?" A profiler answers "where inside this code does the time go?" They work together. A profiler points you at a hot function, and a benchmark tells you whether your fix to that function helped.
The problem with a quick timing
The simplest approach is to wrap the code in a timer and print the result:
use std::time::Instant;
fn sum_to(n: u64) -> u64 {
(0..n).sum()
}
fn main() {
let start = Instant::now();
let result = sum_to(1_000_000);
let elapsed = start.elapsed();
println!("result = {result}, took {elapsed:?}");
}This runs, and it prints a number. The number is unreliable for several reasons.
- One sample is one data point. The first run often pays for cold CPU caches, page faults, and lazy initialization. Another process may take the CPU in the middle of your run. You cannot tell whether the number you saw is typical.
- Timer resolution and overhead. Calling
Instant::now()costs time itself. If the code under test takes tens of nanoseconds, the timer's own cost and granularity are a large share of what you read. - The compiler may remove the work. In a release build, the optimizer can see that
sum_to(1_000_000)has a known input and no side effects. It may compute the answer at compile time, so the loop you meant to time never runs. This is the most common way a hand-written benchmark produces a result that is wrong by orders of magnitude. The chapter onblack_boxcovers it in detail. - Debug builds mislead.
cargo runbuilds without optimizations by default. Timings from a debug build say little about the code your users will run. - No way to tell signal from noise. Suppose you run the program twice and get 310 µs and 290 µs. You cannot say whether the 20 µs gap is a real difference or ordinary variation.
You can fix some of these by hand. You can loop many times, discard the first runs, compute a mean and a standard deviation, and repeat the process after each change. That is exactly the work Criterion does for you, and doing it carefully yourself is tedious and easy to get subtly wrong.
Why Criterion
Criterion.rs is a statistics-driven benchmarking library for Rust. It runs on stable Rust and integrates with cargo bench. These are its main features:
- Warm-up and many samples. Criterion runs your code for a warm-up period, then collects many timing samples. Each sample times a batch of iterations, so very fast functions are still measured accurately.
- Statistical analysis. It reports an estimate with a confidence interval rather than a single number. It also detects outliers in the samples.
- Change detection. Criterion stores the results of the previous run. On the next run it tests whether performance changed and reports whether the change is statistically significant or within the noise.
- Reports. The console output gives a summary. With the
html_reportsfeature enabled, Criterion also writes HTML pages with plots of the distributions, intarget/criterion. - Parameterized benchmarks. You can run the same code over several input sizes and compare the results side by side.
- Throughput. You can tell Criterion how many bytes or elements each iteration processes, and it reports MB/s or elements per second as well as time.
- Baselines. You can save a run under a name and compare later runs against it.
The way these pieces fit together is a feedback loop:
How it compares with other options
Criterion is not the only way to measure Rust code. The right tool depends on the question.
| Tool | What it measures | Typical use |
|---|---|---|
| `Instant` in `main` | One wall-clock duration | A rough check during development |
| Built-in `#[bench]` | Wall-clock time per iteration | Requires the nightly compiler and is unstable, so it is not suitable for most projects |
| Criterion.rs | Wall-clock time with statistics and change detection | Micro-benchmarks and small components, on stable Rust |
| Divan | Wall-clock time, with a different macro-based API | An alternative to Criterion for the same kind of work |
| `hyperfine` | Wall-clock time of a whole command-line program | Comparing complete executables rather than functions |
| Instruction-counting tools such as Iai | CPU instructions, not time | Environments where timing is too noisy, such as shared CI machines |
Criterion measures wall-clock time, which is what users experience, but wall-clock time is also affected by everything else running on the machine. That is the source of most of the noise discussed in the pitfalls chapter.
What Criterion does not do
Knowing the limits keeps your expectations accurate.
- It does not tell you why code is slow. For that you need a profiler or flame graph.
- It does not make results portable. A number measured on your laptop does not transfer to a server with a different CPU, memory, or load. Compare results from the same machine and the same conditions.
- It does not fix a badly designed benchmark. If you measure setup work along with the code under test, or feed the function unrealistic input, Criterion will report an accurate measurement of the wrong thing.
- It is not a good fit for long-running operations. Criterion collects many samples by default, so a function that takes seconds per call makes the run very slow unless you reduce the sample count. The configuration chapter covers how to tune this.
- It is not an end-to-end load test. Micro-benchmarks isolate small pieces of code. They do not capture interactions such as contention between threads or network latency.
What the rest of the tutorial builds
The remaining chapters follow the same loop shown in the diagram. You will set up a Cargo bench target with harness = false, write a first benchmark, and keep the compiler from removing your work with black_box. You will then learn how Criterion samples and what its output means, compare several inputs with groups and BenchmarkId, keep setup out of the timing with iter_batched, and report throughput. The last chapters cover configuration, baselines, noise, and running benchmarks in continuous integration.
By the end you should be able to take a performance question about your own code, turn it into a benchmark, and judge whether the result is trustworthy.
Exercise
A colleague times a function once with Instant::now() in a debug build and reports "the new version is 15% faster." Name three reasons this conclusion may be wrong.
Show answer
Any three of these: (1) one sample cannot separate a real difference from run-to-run variation such as cold caches or other processes; (2) a debug build has no optimizations, so the timing does not describe release behavior; (3) in a release build the compiler might remove or precompute the work, so the measurement would be meaningless; (4) timer overhead and resolution distort short measurements; (5) there is no statistical test showing the 15% difference is outside the noise.
Exercise
Your benchmark shows that a function is slow, but you do not know which part of it is responsible. Is Criterion the right tool to answer that, and what would you use?
Show answer
No. Criterion tells you how long the function takes and whether a change altered that time. To find which part of the function is responsible, use a profiler or flame graph, then use Criterion to confirm that your fix improved the measured time.