Sub topic 3
Inlining, Stack Unwinding, and Comparing Flamegraphs
This chapter assumes basic Rust and Cargo usage, release builds, command-line tools, and the idea of a call stack.
Inlining, Generics, and Mangled Names
The compiler may inline a function by placing its body inside the caller. This removes call overhead, but the flamegraph may show the work under the caller instead of the original function. Optimization can therefore change the graph without changing the actual work.
Generic Rust functions are compiled into specialized versions for each used type. Their names may be long and mangled. Debug symbols let tools translate these names into readable source locations. Use the search feature in your SVG viewer to find a function or module.
Frame Pointers or DWARF: Getting Complete Stacks
A profiler must unwind the current stack to record callers. Frame pointers make this process simple and reliable, but they can add a small runtime cost. DWARF unwind information avoids that cost in many cases, though unwinding can be slower or incomplete in optimized code.
For difficult profiles, build with frame pointers:
RUSTFLAGS="-C force-frame-pointers=yes" cargo build --releaseUnder the Hood: perf and inferno
On Linux, perf periodically records instruction pointers and call stacks. Inferno converts those stacks into folded text and then an SVG:
perf record -F 99 -g -- ./target/release/myapp
perf script | inferno-collapse-perf | inferno-flamegraph > flame.svgFixing and Verifying a Hotspot
A wide frame indicates many samples, so it often identifies CPU-heavy work. Change one cause at a time, then run a benchmark with the same input and environment. A flamegraph explains where time went; a benchmark measures whether total time improved.
For example, trial division should stop at the square root of the candidate:
fn is_prime(n: u64) -> bool {
if n < 2 {
return false;
}
(2..).take_while(|d| d * d <= n).all(|d| n % d != 0)
}Differential Flamegraphs
Record profiles before and after the change, fold both captures, and compare them:
inferno-diff-folded before.folded after.folded | inferno-flamegraph > diff.svgThe differential graph highlights frames that grew or shrank.
Threads, Async, and Off-CPU Time
Threaded programs combine samples from many threads. Inspect thread labels or profile specific workloads. Async stacks can stop at an executor because the logical caller is stored in a future rather than a normal stack.
CPU flamegraphs show time running on a CPU. They do not show time waiting for files, locks, network responses, or timers. Use off-CPU or scheduling tracing when waiting is the suspected bottleneck.
Exercise
Why might an inlined function be missing from a flamegraph?
Show answer
Its work may appear inside the caller because the compiler removed the separate call frame.