Sub topic 1
Profiling Rust Programs with Flamegraphs
Prerequisites
Assume you know basic Rust and Cargo, can use a command line, and understand that functions call other functions.
Call stacks: the raw material of a profile
A call stack is the chain of active function calls at one moment. The last function is currently running. Its callers appear below it. For example, main might call count_primes, which calls is_prime.
fn is_prime(n: u64) -> bool {
n >= 2 && (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));
}A profiler records many such stacks. It can then show which call paths were active most often.
How sampling profilers work
A sampling profiler interrupts a running program at regular intervals, such as 99 times per second. At each interrupt, it records the current stack and then lets the program continue. It does not trace every function call.
If a function appears in 30% of samples, the program probably spent about 30% of its CPU time in that function or in functions it called. This is an estimate, so use a long, repeatable workload and enough samples.
Anatomy of a flamegraph
A flamegraph merges identical stacks into horizontal rectangles:
- The bottom row contains entry points such as
main. - A rectangle above another rectangle is a function it called.
- Wider rectangles represent more samples, and therefore more estimated CPU time.
- The vertical position shows call depth, not time.
- Colors usually help distinguish frames but do not measure performance.
Building Rust for profiling: release mode with debug symbols
Profile release code because debug builds change optimization and runtime behavior. Keep debug information so profilers can translate machine addresses into function names and source lines.
Add this to Cargo.toml:
[profile.release]
debug = trueThen build with:
cargo build --releaseDebug symbols do not turn off release optimizations. They make the optimized binary easier to inspect.
Exercise
Why should a CPU flamegraph rectangle be interpreted as an estimate rather than an exact timing measurement?
Show answer
It is based on periodic samples, so it estimates time and can miss work between samples.