Sub topic 1
Why Benchmark, and Why Criterion
Prerequisites
This chapter assumes you can do the following:
- Read and write basic Rust: functions, closures, and modules.
- Build, test, and run projects with Cargo.
- Edit
Cargo.tomland add dev-dependencies. - Explain in general terms what performance and runtime mean.
You do not need prior experience with benchmarking. This chapter covers why it matters and what Criterion offers. Later chapters cover the setup and the code.
Why measure performance
Code that looks slow is often fast, and code that looks fast is often slow. Intuition about performance fails for several reasons:
- The compiler rewrites your code heavily in release mode, so the source is a poor guide to what runs.
- CPU caches, branch prediction, and memory layout change costs in ways that are hard to predict.
- The input matters. An algorithm that wins on 10 items can lose on 10,000.
A benchmark is a repeatable program that measures how long a piece of code takes to run. It replaces guessing with numbers. You can then answer questions such as these:
- Did this refactor make the parser slower?
- Which of two implementations is faster for my real input sizes?
- Is this function worth optimizing at all?
A benchmark also guards against regressions. A regression is a change that makes code slower than before. Without measurements, regressions often go unnoticed until users complain.
Why not time it yourself
The simplest approach is to wrap a call in std::time::Instant and print the elapsed time. For example:
use std::time::Instant;
fn work(n: u64) -> u64 {
(0..n).sum()
}
fn main() {
let start = Instant::now();
let result = work(10_000);
println!("result {result}, took {:?}", start.elapsed());
}This runs, but the number it prints is unreliable:
- It is a single sample. One run can be slow because of a context switch, a cold cache, or another process.
- It may include startup costs, such as first-time page faults, that do not reflect steady-state speed.
- The compiler may compute the result at compile time, so you measure almost nothing.
- It gives no sense of spread, so you cannot tell whether a 5% difference is real or just noise.
Good benchmarking needs many runs, a warm-up period, and statistics. Writing that yourself is tedious and easy to get wrong.
Why Criterion
Criterion.rs is a statistics-driven benchmarking library for Rust. It works on stable Rust, which matters because the built-in #[bench] attribute is only available on nightly. Criterion handles the repetitive parts for you:
| Task | By hand | With Criterion |
|---|---|---|
| Warm up the code | Write your own loop | Automatic |
| Choose iteration counts | Guess | Chosen to fit the time budget |
| Collect many samples | Write your own loop | Automatic |
| Estimate spread and outliers | Write the statistics | Reported for each benchmark |
| Detect change versus the last run | Compare by eye | Statistical test, reported in the output |
| Visualize results | Build your own charts | HTML reports with plots |
| Compare against a saved run | Store and diff files | Named baselines |
Criterion runs your code many times, then analyzes the timings to estimate the typical cost and the uncertainty around it. When you run it again after a code change, it compares the new run to the previous one and tells you whether performance changed, and how confident it is.
How the pieces fit together
The diagram shows the workflow you will build over this tutorial.
Each later chapter covers one stage. You will configure Cargo, write a benchmark, learn to stop the compiler from removing your work, and learn to read the results.
What benchmarking cannot tell you
Benchmarks have limits, and you should keep them in mind:
- A micro-benchmark measures a small piece of code in isolation. Real programs have different cache behavior and contention.
- Results depend on the hardware, the operating system, and background load.
- A faster function does not always make the program faster. Profile first to find where the time goes, then benchmark the hot spots you find.
Benchmarking answers "how fast is this code, and did it change?" Profiling answers "where is my program spending time?" You will often use both.
Exercise
Give two reasons a single Instant::now() / elapsed() measurement is unreliable, and name one thing Criterion does to address each.
Show answer
Examples: (1) It is one sample, so noise from the scheduler or a cold cache can dominate. Criterion collects many samples and reports statistics. (2) It has no warm-up, so first-run costs are included. Criterion runs a warm-up phase before sampling. (3) The compiler may optimize the work away. Criterion provides black_box, covered in a later chapter, to prevent this.