Sub topic 11
Fixing a hotspot and verifying the result
This chapter assumes you can build and run Rust programs with Cargo, that you have already produced a flamegraph of the prime-counting program with cargo flamegraph, and that you can read it well enough to see that is_prime dominates the time. Here we fix that hotspot and then prove the fix helped.
A flamegraph tells you where time goes. It does not tell you how much faster a change made the program, and it can mislead you about small differences. Verifying an optimization takes a separate, repeatable measurement.
From hotspot to hypothesis
The program from the earlier chapters looks like this:
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 flamegraph shows a wide is_prime frame, and the all iterator and the remainder operation take nearly all of that width. The width tells you where the time goes. It does not tell you why. To choose a fix, turn what you see into a hypothesis.
Here the hypothesis is: is_prime(n) tests every divisor from 2 to n - 1. If n has a divisor larger than its square root, it also has a matching divisor smaller than the square root. So testing only divisors up to the square root gives the same answer with far fewer remainder operations.
Writing the hypothesis down gives you two things to check later. The output must stay the same, and the time must drop by about the amount you predicted.
Apply the fix
Replace the divisor range so that the loop stops once d * d exceeds n:
fn is_prime(n: u64) -> bool {
if n < 2 {
return false;
}
(2..).take_while(|d| d * d <= n).all(|d| n % d != 0)
}For n near 100,000, the old loop could run about 100,000 times for a prime. The new loop runs at most about 316 times, since 316 squared is just under 100,000. Composite numbers usually exit early in both versions, so the saving is largest for primes.
The fix also changes the overflow behavior. The expression d * d is computed in u64. For the inputs here it cannot overflow, but if you raise the limit toward u64::MAX, d * d could overflow and panic in debug builds or wrap in release builds. For large inputs, compare with d <= n / d instead.
Check correctness before speed
A faster function that returns wrong answers is worse than a slow one. Before measuring time, confirm that behavior is unchanged. A small test that compares the new function with the original, kept as a reference, does this:
#[cfg(test)]
mod tests {
fn is_prime_slow(n: u64) -> bool {
if n < 2 {
return false;
}
(2..n).all(|d| n % d != 0)
}
fn is_prime_fast(n: u64) -> bool {
if n < 2 {
return false;
}
(2..).take_while(|d| d * d <= n).all(|d| n % d != 0)
}
#[test]
fn fast_matches_slow() {
for n in 0..10_000 {
assert_eq!(is_prime_slow(n), is_prime_fast(n), "mismatch at {n}");
}
}
}Run it with cargo test. The test covers the edge cases 0, 1, and 2 as well as perfect squares such as 4, 9, and 25. Perfect squares are the classic place for an off-by-one error in a square-root bound, which is why <= matters in the condition.
Profile again
Rebuild and profile with the same command and the same workload as before:
cargo flamegraph --bin myappKeep everything else identical. If you change the workload, the sampling frequency, or the machine's load between runs, you cannot attribute the difference to your code change.
The new flamegraph looks different in two ways. The is_prime frame is much narrower relative to the whole, and other frames, such as count_primes internals, process startup, and the println! call, now take a larger share. Percentages in a flamegraph are always relative to the total samples of that run. A function can get faster in absolute terms and still show a wider frame if everything else got faster even more.
Because of this, you cannot compare two flamegraphs by looking at frame widths alone. The total run time is different, so the same width means a different amount of time. This is the reason for the next step.
Measure with a benchmark
A flamegraph is built from samples taken about 99 times per second. A short program yields a handful of samples, which is too few to measure a speedup precisely. A benchmark runs the code many times and reports statistics.
Criterion is a common benchmarking crate for Rust. Add it as a development dependency and declare the benchmark target in Cargo.toml:
[dev-dependencies]
criterion = "0.5"
[[bench]]
name = "primes"
harness = falseThen create benches/primes.rs. Benchmarks in benches/ are compiled as a separate crate, so the function under test must be reachable from it. The simplest way to keep this example self-contained is to include the functions in the benchmark file:
use criterion::{black_box, criterion_group, criterion_main, Criterion};
fn is_prime(n: u64) -> bool {
if n < 2 {
return false;
}
(2..).take_while(|d| d * d <= n).all(|d| n % d != 0)
}
fn count_primes(limit: u64) -> usize {
(0..limit).filter(|&n| is_prime(n)).count()
}
fn bench_count_primes(c: &mut Criterion) {
c.bench_function("count_primes_100k", |b| {
b.iter(|| count_primes(black_box(100_000)))
});
}
criterion_group!(benches, bench_count_primes);
criterion_main!(benches);The call to black_box hides the input value from the optimizer. Without it, the compiler could evaluate the whole computation at compile time and the benchmark would measure nothing.
Run the benchmark on the old code first and save it as a named baseline, then run it on the new code and compare:
# with the original is_prime in place
cargo bench -- --save-baseline before
# after applying the fix
cargo bench -- --baseline beforeCriterion prints the change in time with a confidence interval and a p-value, for example a report that the time changed by a large negative percentage and "Performance has improved." Use the reported interval, not a single run's number. If the interval is wide, or Criterion reports "No change in performance detected," your fix may not have helped, or the machine was too noisy to tell.
Reducing measurement noise
Benchmark results vary with other activity on the machine. Several habits reduce the noise:
- Close other heavy programs, including browsers and builds.
- Run on mains power and keep the same power profile, because laptops change CPU frequency to save energy.
- Run the benchmark more than once. A result you can reproduce is more trustworthy than a single good number.
- Compare before and after on the same machine, in the same session.
Putting the workflow together
The full loop has the same shape each time, and you repeat it for every hotspot.
Change one thing at a time. If you apply three changes and the program gets faster, you do not know which one helped. If it gets slower, you do not know which one hurt.
When the speedup is smaller than expected
Sometimes a fix looks right on the flamegraph but the benchmark shows little gain. Common reasons:
- The benchmark workload differs from the profiled workload. If you profiled with 100,000 and benchmark with 100, the hotspot may not appear at all.
- The profile was dominated by a cost that the benchmark does not include, such as startup, file reading, or printing.
- The compiler had already optimized the code in a way that hid the difference. Inlining can make a function disappear from the graph while its cost remains in the caller.
- Noise hides a small real improvement. Increase the sample size or run on a quieter machine.
If the benchmark shows a regression you did not expect, compare the two profiles directly. The next chapters cover differential flamegraphs, which show exactly which frames grew or shrank.
Summary of the verification checklist
| Check | Tool | Question answered |
|---|---|---|
| Correctness | `cargo test` | Does the new code return the same results? |
| Hotspot moved | Flamegraph | Did the targeted frame shrink? |
| Real speedup | Criterion baseline | How much faster, with what confidence? |
| Same conditions | Same workload and machine | Is the comparison fair? |
Exercise
After your fix, the new flamegraph shows is_prime at 40% of the width, down from 95%. A colleague says this means the program is now 2.4 times faster (95 / 40). Why is that conclusion unreliable, and how would you get a trustworthy number?
Show answer
Frame widths are percentages of the total samples in that run, and the total run time differs between the two runs. The 95% and the 40% refer to different amounts of time, so dividing them does not give a speedup. To get a trustworthy figure, benchmark both versions on the same workload and machine, for example with Criterion's --save-baseline and --baseline options, and read the reported change with its confidence interval.
Exercise
Your square-root version uses the condition d * d <= n. Suppose you wrote d * d < n instead. Which inputs would give wrong answers, and which test in this chapter would catch it?
Show answer
Perfect squares of primes, such as 4, 9, 25, and 49, would be reported as prime, because the loop would stop before testing the divisor equal to the square root. The fast_matches_slow test would catch it, because it compares both functions for every n from 0 to 9,999 and 4 is in that range.