Sub topic 11
Fixing a hotspot and verifying the result
This chapter assumes you can build Rust in release mode, have already produced a flamegraph with cargo flamegraph, and can read the wide boxes in it. Here you fix the hotspot from the earlier example and then confirm the fix with measurements instead of impressions.
The hotspot
The example program counts primes below 100,000 using trial division. The first flamegraph showed almost all samples under is_prime, in the closure that tests every divisor from 2 up to n.
fn is_prime(n: u64) -> bool {
if n < 2 {
return false;
}
(2..n).all(|d| n % d != 0)
}
fn count_primes(limit: u64) -> usize {
(0..limit).filter(|&n| is_prime(n)).count()
}
fn main() {
println!("{}", count_primes(100_000));
}The graph tells you where the time goes. It does not tell you the fix. Here the fix comes from the algorithm: a number that has a divisor larger than its square root must also have one smaller than its square root, so you only test divisors d where d * d <= n.
fn is_prime(n: u64) -> bool {
if n < 2 {
return false;
}
(2..).take_while(|d| d * d <= n).all(|d| n % d != 0)
}Why a second flamegraph is not enough
After the change, you could profile again and see that is_prime is narrower. That is useful, but it has limits.
- A flamegraph shows proportions. If the whole program gets faster, the remaining functions can look wider even though nothing got slower.
- Sampling is statistical. Small differences fall inside the noise.
- The graph has no total time on it, so it cannot say "2x faster".
To get a number, use a benchmark. A benchmark runs the code many times, measures wall-clock time, and reports a typical value with its spread.
Measuring with a benchmark
Criterion is a common benchmark crate. Put the code in a library so the benchmark can call it. Keep the old and new versions side by side while you compare them.
[dev-dependencies]
criterion = "0.5"
[[bench]]
name = "primes"
harness = falseuse criterion::{black_box, criterion_group, criterion_main, Criterion};
fn is_prime_slow(n: u64) -> bool {
n >= 2 && (2..n).all(|d| n % d != 0)
}
fn is_prime_fast(n: u64) -> bool {
n >= 2 && (2..).take_while(|d| d * d <= n).all(|d| n % d != 0)
}
fn count(limit: u64, f: fn(u64) -> bool) -> usize {
(0..limit).filter(|&n| f(n)).count()
}
fn bench(c: &mut Criterion) {
// Check that both versions agree before comparing speed.
assert_eq!(count(10_000, is_prime_slow), count(10_000, is_prime_fast));
let mut group = c.benchmark_group("count_primes");
group.bench_function("slow", |b| {
b.iter(|| count(black_box(20_000), is_prime_slow))
});
group.bench_function("fast", |b| {
b.iter(|| count(black_box(20_000), is_prime_fast))
});
group.finish();
}
criterion_group!(benches, bench);
criterion_main!(benches);Save this as benches/primes.rs and run it:
cargo benchThe benchmark uses a smaller limit than the program so each iteration stays short. Criterion prints a time range for each function. Compare the two ranges. If they do not overlap, the difference is real.
Checklist for a trustworthy comparison
- Check correctness first. The
assert_eq!above stops the benchmark if the fast version gives a different answer. - Use
black_boxon inputs so the compiler cannot precompute the result. - Use the same input size, build profile and machine state for both versions.
- Close other heavy programs. Background load adds noise.
- Change one thing at a time. Otherwise you cannot tell which change helped.
The loop
Profiling is a cycle. You repeat it until the program is fast enough or the remaining hotspots are not worth the effort.
After a fix, profile again. The old hotspot is smaller, and a different function is now the widest box. That one is the next candidate.
Exercise
You rewrite a function and the new flamegraph shows it as a much narrower box. Why should you still run a benchmark before claiming a speedup?
Show answer
A flamegraph shows each function's share of samples, not absolute time, and it carries sampling noise. A benchmark measures actual run time with a spread, so it can show how much faster the code is and whether the difference is larger than the noise.
Exercise
Why does the benchmark above call assert_eq! on the two versions' results before timing them?
Show answer
A faster function is worthless if it returns wrong answers. The assertion confirms that both versions agree on the output, so any speed difference is a real improvement and not a bug.