Sub topic 10
Under the hood: perf record and inferno
This chapter opens up what cargo flamegraph does for you. You will run the pipeline by hand: record samples with perf, fold them into counted stacks, and render an SVG with the inferno tools. Knowing each stage helps you fix broken profiles and tune the sampling.
Prerequisites
This chapter assumes you can:
- Build a Rust program in release mode with
cargo build --release. - Read a basic flamegraph, as covered in the earlier chapters.
- Use a Linux shell.
perfis a Linux tool. On macOS,cargo flamegraphusesdtrace, and the steps below do not apply directly.
You also need perf installed. On Debian or Ubuntu it comes with the linux-tools packages. Install the inferno command-line tools with cargo install inferno.
The four stages
A flamegraph is the end of a short pipeline. Each stage reads the output of the one before it.
| Stage | Tool | Input | Output |
|---|---|---|---|
| Record | `perf record` | A running process | Binary file `perf.data` |
| Dump | `perf script` | `perf.data` | One text block per sample |
| Fold | `inferno-collapse-perf` | Text blocks | One line per unique stack, with a count |
| Render | `inferno-flamegraph` | Folded lines | SVG |
Preparing the build
The pipeline can only show what the binary and the unwinder provide. Two settings matter: debug symbols and a way to walk the stack.
Keep optimizations on, and keep symbols in the release profile:
[profile.release]
debug = trueThen build with frame pointers. A frame pointer is a CPU register that each function sets up so a profiler can follow the chain of callers. Rust omits it by default for speed, so you ask for it:
RUSTFLAGS="-C force-frame-pointers=yes" cargo build --releaseWithout frame pointers, perf record -g often produces short or truncated stacks. The flamegraph then looks flat, with many shallow towers. The previous chapter covers the alternative, DWARF unwinding, and its costs.
A program to profile
Use the same deliberately slow program from earlier. Its time is dominated by is_prime.
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));
}Assume the package is called myapp.
Stage 1: perf record
Run the full pipeline once, then look at each part.
RUSTFLAGS="-C force-frame-pointers=yes" cargo build --release
perf record -F 99 -g -- ./target/release/myapp
perf script | inferno-collapse-perf | inferno-flamegraph > flame.svgThe perf record command has three parts worth understanding:
-F 99sets the sampling frequency to 99 samples per second. At each tick the kernel interrupts the CPU and records what the program was doing.-gasks for call graphs. Each sample stores the whole stack, not only the current function.--ends theperfoptions. Everything after it is the command to profile, including its own arguments.
When the program exits, perf writes perf.data in the current directory. If you see a permissions error, the kernel setting kernel.perf_event_paranoid is probably too strict for your user. Lowering it needs administrator rights, and running perf with sudo is the other common workaround.
Why 99 and not 100
A sampling rate of exactly 100 Hz can line up with work the program does on a 10 ms timer. Every sample would then land at the same point in a cycle, and the profile would be biased. An odd rate such as 99 avoids that lockstep.
Choosing a frequency
More samples give finer detail but cost more overhead and larger files. Fewer samples keep overhead low but make small functions disappear.
| Frequency | Good for | Risk |
|---|---|---|
| 99 Hz | Programs that run for several seconds | Short runs give few samples |
| 999 Hz | Short runs, or finding smaller hotspots | More overhead, larger `perf.data` |
| 4999 Hz and above | Very short runs | Can distort the program being measured |
For the example program, the run lasts long enough at 99 Hz to produce a few hundred samples. If your run lasts under a second, raise -F to get enough data. As a rough rule, aim for at least a few hundred samples before trusting percentages.
Stage 2: perf script
perf.data is a binary file. perf script converts it to text. Run it alone to see what a sample looks like:
perf script | head -n 20Each sample is one block. It has a header line with the process name, process ID, timestamp and event. Below that is one line per stack frame, innermost function first. Each frame line shows an address, a symbol name, and the binary it came from.
Check this output when a flamegraph looks wrong. If you see raw addresses like 0x55d2c0a1b2c3 where function names should be, symbols are missing. If every stack has one or two frames, unwinding failed.
Stage 3: inferno-collapse-perf
The collapse step turns thousands of sample blocks into a short list. It joins each stack into a single line with frames separated by semicolons, then appends the number of times that exact stack was seen. The result is called folded stacks.
A folded file looks like this:
myapp;_start;main;myapp::main;myapp::count_primes;myapp::is_prime 412
myapp;_start;main;myapp::main;myapp::count_primes 3Read each line from left to right: outermost caller first, innermost function last. The number is the sample count. In this made-up excerpt, is_prime was the innermost function in 412 samples.
This format is plain text. You can filter it with ordinary tools before rendering. For example, you can keep only stacks that pass through one function:
perf script | inferno-collapse-perf | grep count_primes > only_count.folded
inferno-flamegraph < only_count.folded > only_count.svgFolded files are also the input to differential flamegraphs, which a later chapter covers.
Stage 4: inferno-flamegraph
inferno-flamegraph reads folded lines and draws the SVG. The width of each box is proportional to its sample count. Open the file in a browser to get hover text and click-to-zoom.
Useful options include:
--title "my title"sets the heading.--width 1800changes the image width.--colorspicks a palette.--reversebuilds an icicle-style graph that grows downward from the leaf functions.
Use inferno-flamegraph --help to see the full list for your installed version.
How this relates to cargo flamegraph
cargo flamegraph runs the same stages. It builds the target, runs it under perf record, then pipes the output through inferno. The difference is convenience:
cargo install flamegraph
cargo flamegraph --bin myapp
# for a benchmark target:
cargo flamegraph --bench my_bench -- --benchUse the manual pipeline when you need to control a stage. Typical reasons are changing -F, adding perf options, filtering the folded stacks, saving a .folded file for later comparison, or attaching to a process that is already running.
Common errors
- Flat graph with few levels. Stacks were cut short. Rebuild with
force-frame-pointers=yes, or tryperf record --call-graph dwarf. - Hex addresses instead of names. The binary lacks symbols. Check
debug = truein[profile.release]and that you profile the release binary, not a stripped copy. - Very few samples. The run is too short for the frequency. Raise
-F, or give the program more work. - Permission denied from perf. Adjust
kernel.perf_event_paranoidor run with elevated rights. - Standard library frames are missing or shallow. The prebuilt standard library may use frame pointer-free code, so stacks through it can break. This is a known limit of the default toolchain.
Exercises
Exercise
You run perf record -F 99 -g -- ./target/release/myapp and the flamegraph shows many towers only two boxes tall, with no count_primes frame above is_prime. Name the most likely cause and one fix.
Show answer
The stacks are being truncated because the binary has no frame pointers, so perf cannot walk the callers. Rebuild with RUSTFLAGS="-C force-frame-pointers=yes" cargo build --release, or record with perf record --call-graph dwarf.
Exercise
What does the line myapp;main;work;parse 250 in a folded stacks file mean?
Show answer
The exact stack myapp, then main, then work, then parse (outermost to innermost) was seen in 250 samples, with parse as the function running at the moment of each sample.
Exercise
Why is 99 Hz usually preferred over 100 Hz as a sampling rate?
Show answer
100 Hz can sync with periodic work on a 10 ms cycle, so samples would repeatedly hit the same point and bias the profile. An odd rate like 99 Hz avoids that alignment.