Sub topic 2
Choosing a Workload and Reading a Rust Flamegraph
Assume you know basic Rust, Cargo, release builds, and the idea of a call stack. A flamegraph is useful only when the program does representative work for long enough to sample.
Choosing a Workload Worth Profiling
A workload is the input and execution pattern you use during profiling. It should resemble real use and make the suspected slow path run often. Avoid tiny inputs, debug builds, startup-only behavior, and artificial loops that production never performs.
A useful workload has these properties:
- It uses realistic data sizes and distributions.
- It runs for several seconds.
- It avoids unrelated startup and shutdown work.
- It is repeatable, so two profiles can be compared.
- It exercises the feature you want to improve.
For example, this program gives the profiler a clear CPU-heavy path:
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));
}Your First Flamegraph with `cargo flamegraph`
Add debug information to the optimized release profile. Debug information lets tools map samples to function names and source lines without disabling optimization.
[profile.release]
debug = trueInstall the tool and profile the binary:
cargo install flamegraph
cargo flamegraph --bin myappThe command builds and runs the program, samples its call stacks, and writes flamegraph.svg. On Linux, it normally uses perf, which may require permission or kernel configuration.
Reading the Graph: Finding Hotspots
Each box is a function. The horizontal width represents the share of sampled CPU time for that stack. The vertical position represents call depth. Wider boxes are more important than taller boxes.
Start with wide boxes near the bottom, then follow their child boxes upward. A wide child shows where its parent spends time. Do not treat color as a measurement; colors usually help distinguish frames.
A hotspot is a function or call path that accounts for substantial width. Optimize only after confirming that it belongs to the representative workload.
Exercise
What does a wide box near the bottom of a flamegraph usually indicate?
Show answer
A frequently sampled call path and therefore a likely consumer of CPU time.