Sub topic 9
Reporting throughput in bytes or elements
This chapter assumes you can write and run a basic Criterion benchmark with bench_function and Bencher::iter. It also assumes you have used benchmark groups with BenchmarkId, as in the previous chapters. Here you will tell Criterion how much work each iteration does. Criterion then reports a rate such as GiB/s or Melem/s next to the time.
Why time alone is not enough
A benchmark reports time per iteration. That is fine when you compare two versions of the same function on the same input. It is harder to read when the input size changes. Suppose a function takes 4 µs on 16 KiB of data and 64 µs on 256 KiB. Is that good? The second input is 16 times larger and the time is also 16 times larger, so the function scales linearly. You had to do arithmetic to see that.
Throughput does the arithmetic for you. It divides the amount of work per iteration by the measured time:
throughput = work per iteration / time per iterationIf throughput stays flat as the input grows, the cost per unit of work is constant. If it drops at a certain size, something changed. A common cause is the data no longer fitting in a CPU cache. Throughput also lets you compare against known limits, such as memory bandwidth or the speed of a disk or network link.
The Throughput enum
You declare the work with the Throughput enum from the criterion crate. It has these variants:
| Variant | Meaning | Displayed as |
|---|---|---|
| `Throughput::Bytes(n)` | Each iteration processes `n` bytes | KiB/s, MiB/s, GiB/s (powers of 1024) |
| `Throughput::BytesDecimal(n)` | Each iteration processes `n` bytes | KB/s, MB/s, GB/s (powers of 1000) |
| `Throughput::Elements(n)` | Each iteration processes `n` items | elem/s, Kelem/s, Melem/s |
BytesDecimal was added in Criterion 0.5. Use it when you compare against a vendor specification or a network speed quoted in decimal units. Use Bytes for memory-style numbers. The value n is a u64, so convert a usize with as u64.
Choose bytes when the cost scales with the size of the data, as in hashing, compression, parsing, or copying. Choose elements when the cost scales with the number of items, as in sorting records, inserting into a map, or processing messages. If both views make sense, pick the one your readers already use to talk about the problem.
Attaching throughput to a group
Throughput is set on a benchmark group, not on the Criterion handle directly. You call group.throughput(...) before registering a benchmark, and it applies to the benchmarks you register after it.
This example counts spaces in byte buffers of three sizes:
use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion, Throughput};
fn count_spaces(data: &[u8]) -> usize {
data.iter().filter(|&&b| b == b' ').count()
}
fn bench_count_spaces(c: &mut Criterion) {
let mut group = c.benchmark_group("count_spaces");
for size in [1_024usize, 16 * 1_024, 256 * 1_024] {
let data: Vec<u8> = (0..size)
.map(|i| if i % 7 == 0 { b' ' } else { b'x' })
.collect();
group.throughput(Throughput::Bytes(size as u64));
group.bench_with_input(BenchmarkId::from_parameter(size), &data, |b, data| {
b.iter(|| count_spaces(black_box(data)))
});
}
group.finish();
}
criterion_group!(benches, bench_count_spaces);
criterion_main!(benches);Three details matter here:
group.throughputis called inside the loop, once per input size. The value must match the input that the next benchmark uses.- The data is built outside the timed closure. Only
count_spacesis measured. - The declared work (
sizebytes) is the amount of data one call to the routine processes. Criterion does not inspect your code, so it cannot check that this is true.
Reading the throughput line
Once a group has a throughput set, Criterion prints a second line under the time. The numbers below are illustrative, and yours will differ:
count_spaces/16384 time: [4.2310 µs 4.2402 µs 4.2509 µs]
thrpt: [3.5890 GiB/s 3.5981 GiB/s 3.6067 GiB/s]The thrpt line has the same shape as the time line: a lower bound, a best estimate, and an upper bound of the confidence interval. The bounds are in the same order as the numbers on the line above, but they are inverted. A higher time means lower throughput. So the first throughput number comes from the slowest end of the time interval, and the last comes from the fastest end.
You can check the middle value by hand. The routine handled 16,384 bytes in 4.2402 µs:
16384 B / 4.2402e-6 s = 3.864e9 B/s
3.864e9 / 1024^3 = 3.598 GiB/sWhen you run a benchmark a second time, the change-detection block also reports a change in throughput. A 10% drop in time appears as a throughput gain of roughly 11%, because the relation is a reciprocal and not a straight negation. For example, 0.9 times the time gives 1/0.9 = 1.11 times the rate.
Elements for item-based work
When the natural unit is items, use Throughput::Elements. This example parses a batch of numeric strings and reports how many parses per second the code manages:
use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion, Throughput};
fn parse_all(lines: &[String]) -> u64 {
lines
.iter()
.map(|s| s.parse::<u64>().unwrap_or(0))
.sum()
}
fn bench_parse(c: &mut Criterion) {
let mut group = c.benchmark_group("parse_all");
for count in [100usize, 1_000, 10_000] {
let lines: Vec<String> = (0..count).map(|i| (i * 31).to_string()).collect();
group.throughput(Throughput::Elements(count as u64));
group.bench_with_input(BenchmarkId::from_parameter(count), &lines, |b, lines| {
b.iter(|| parse_all(black_box(lines)))
});
}
group.finish();
}
criterion_group!(benches, bench_parse);
criterion_main!(benches);The output reads like thrpt: [58.1 Melem/s 58.4 Melem/s 58.7 Melem/s]. Flat numbers across the three sizes mean per-item cost does not depend on batch size. A fall at 10,000 would point to a memory effect or an algorithm with worse than linear cost.
Throughput with other measurement styles
Throughput describes one iteration of the measured routine. That has consequences for the other bencher methods you know.
With iter_batched, the setup closure is not timed, and the throughput applies to the routine closure only. If the setup clones a vector of 1,000 items and the routine sorts it, declare Throughput::Elements(1_000):
use criterion::{black_box, criterion_group, criterion_main, BatchSize, Criterion, Throughput};
fn bench_sort(c: &mut Criterion) {
let data: Vec<u32> = (0..1000).rev().collect();
let mut group = c.benchmark_group("sort");
group.throughput(Throughput::Elements(data.len() as u64));
group.bench_function("1000 reversed", |b| {
b.iter_batched(
|| data.clone(),
|mut v| {
v.sort();
black_box(v)
},
BatchSize::SmallInput,
)
});
group.finish();
}
criterion_group!(benches, bench_sort);
criterion_main!(benches);Here the result is the number of elements sorted per second. The clone cost is excluded from both the time and the rate.
If one iteration of your closure loops internally, count the total work in that loop. A closure that calls count_spaces ten times on a 1 KiB buffer processes 10,240 bytes per iteration, not 1,024.
Setting it per benchmark in a group
The throughput on a group is sticky: it stays in effect until you change it. This makes one mistake easy. Say you write a group with two benchmarks that handle different amounts of data, but you call group.throughput only once before both. Both will report rates using the first value, and the second rate will be wrong with no warning.
Set the throughput immediately before each bench_function or bench_with_input call whose work differs. In a loop over sizes, put the call inside the loop, as in the examples above.
Choosing between bytes and elements
Pick the unit that makes the rate meaningful for your decision:
- A checksum, codec, or parser is usually compared in bytes per second, because other tools publish the same number.
- A data structure operation such as an insert or lookup is better in elements per second, because each operation is the unit of interest.
- Do not switch units between versions of a benchmark. Saved baselines and the change report compare like with like, so a unit change makes old results hard to interpret.
Throughput is derived from time, so it has the same noise as the time measurement. Treat a rate as a convenient view of the same data. A throughput that moves by 2% in either direction between runs without a code change is noise, just as a 2% time change would be.
Exercises
Exercise
A benchmark processes a 64 KiB buffer (65,536 bytes) and Criterion estimates 20 µs per iteration. What throughput should the thrpt line report, in GiB/s, if you declared Throughput::Bytes(65_536)?
Show answer
65,536 B / 20e-6 s = 3.277e9 B/s. Dividing by 1024^3 (1,073,741,824) gives about 3.05 GiB/s. With Throughput::BytesDecimal(65_536) the same run would print about 3.28 GB/s.
Exercise
A group has two benchmarks, one on 1,000 items and one on 5,000 items. The code calls group.throughput(Throughput::Elements(1_000)) once at the top of the group. What is wrong with the rates, and how do you fix it?
Show answer
The throughput setting persists, so the 5,000-item benchmark is also divided by 1,000 elements. Its rate is reported at one fifth of the real value. Call group.throughput again with Throughput::Elements(5_000) immediately before registering the second benchmark, or set it inside the loop that creates each benchmark.
Exercise
In an iter_batched benchmark, the setup closure builds a vector of 500 numbers and the routine sums it. Which Throughput value should you declare, and is the setup time included in the rate?
Show answer
Declare Throughput::Elements(500), because the routine processes 500 items per iteration. The setup time is not included, since iter_batched times only the routine closure.