Sub topic 6
Your first flamegraph with cargo flamegraph
This chapter takes you from an unprofiled Rust project to a flamegraph.svg file you can open in a browser. It assumes you can build and run a Cargo project in release mode, use a terminal, and know what a call stack is. The earlier chapters covered how sampling works, how a flamegraph is laid out, and why release builds need debug symbols. Here you put those pieces to work.
What cargo flamegraph does
cargo flamegraph is a Cargo subcommand. It wraps the whole profiling workflow in one command:
- It builds your target with the release profile.
- It runs the program under the platform's sampling profiler. On Linux that is
perf. On macOS it usesdtrace, and on Windows it usesblondie. - It converts the raw samples into folded stacks.
- It renders the folded stacks as
flamegraph.svgin the current directory.
Under the hood it uses the inferno crate for the last two steps. A later chapter shows how to run those steps by hand.
Prepare the project
Create a new binary project and name it myapp:
cargo new myapp
cd myappBefore profiling, make sure the release profile keeps debug information. Without it, the graph still shows function names in most cases, but you lose source lines, and stacks through some code can be cut short or merged. Open Cargo.toml and add:
[profile.release]
debug = trueThis keeps all optimizations on. It only adds debug info to the binary, so the speed you measure is the speed your release build really has. The binary gets larger, but the machine code is the same.
Now replace src/main.rs with a deliberately slow program. It counts primes below 100,000 by trial division, and nearly all of its time goes into one loop:
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));
}Run it once with cargo run --release to confirm it works. It prints 9592 and takes a noticeable fraction of a second to a few seconds, depending on your machine. That is long enough for a profiler to collect plenty of samples.
Install the tool and its prerequisites
Install the subcommand with Cargo:
cargo install flamegraphThis puts a cargo-flamegraph binary (and a standalone flamegraph binary) in ~/.cargo/bin. Make sure that directory is on your PATH.
On Linux you also need perf. Package names differ by distribution:
- Debian and Ubuntu:
linux-tools-commonplus thelinux-tools-genericpackage that matches your kernel. - Fedora:
perf. - Arch:
perf.
On macOS, dtrace ships with the system, but it needs elevated privileges. On Windows, the tool uses blondie and must run from an elevated shell.
Generate the flamegraph
From the project directory, run:
cargo flamegraph --bin myappYou will see Cargo build the release binary, then a message that perf is recording, then the program's output (9592), and finally a note that flamegraph.svg was written. Open that file in a web browser. A browser matters because the SVG is interactive: you can hover for details and click to zoom.
If your package has only one binary, --bin is optional, but naming it avoids confusion once a project grows more targets.
Profiling other targets
The same command works for other kinds of targets. For a benchmark, pass the benchmark name, then -- and the arguments the benchmark harness needs:
cargo flamegraph --bench my_bench -- --benchThe --bench after the double dash tells the benchmark harness to run in benchmark mode. Everything after -- goes to the program being profiled, not to cargo flamegraph. Use the same pattern to pass command-line arguments or an input file to your own binary.
Permissions on Linux
The most common first-run failure is a permission error from perf. Linux limits unprivileged profiling through the kernel.perf_event_paranoid setting. Check it:
cat /proc/sys/kernel/perf_event_paranoidValues of 2 or higher block most profiling of kernel code and can block user-space sampling too, depending on the distribution. Lowering it for the current boot is the least invasive fix:
sudo sysctl -w kernel.perf_event_paranoid=1That change is lost at reboot. Alternatively, you can let cargo flamegraph escalate by using the --root flag, which runs the profiler with sudo:
cargo flamegraph --root --bin myappRunning as root may leave flamegraph.svg owned by root. If later runs fail to overwrite it, delete the file or fix its ownership with chown.
Inside containers and some virtual machines, perf may be blocked or unable to access hardware counters. If you profile in Docker, you typically need extra capabilities (such as --cap-add SYS_ADMIN) or a relaxed seccomp profile. In virtual machines without a virtual PMU, perf falls back to a software clock, which still works for CPU flamegraphs but with lower precision.
Useful options
| Option | What it does |
|---|---|
| `--bin NAME` | Profile the named binary target |
| `--bench NAME` | Profile the named benchmark |
| `--example NAME` | Profile the named example |
| `--freq N` | Sample at N hertz instead of the default |
| `--output FILE` | Write the SVG to FILE instead of `flamegraph.svg` |
| `--root` | Run the profiler through `sudo` |
| `--dev` | Profile the dev profile instead of release |
| `--no-inline` | Skip inlined-function expansion to speed up post-processing |
Run cargo flamegraph --help to see the options your installed version supports, since flags change between releases. Keep the default release profile for real measurements. The --dev option exists for debugging the tooling, not for judging performance, because unoptimized code spends its time in different places.
What you should see
Open the SVG. Because of the layout rules from the anatomy chapter, the width of each box is the share of samples that included that function, and the y-axis is stack depth.
For this program, expect the following from the bottom up:
- Runtime frames at the base, such as
_start,__libc_start_mainandstd::rt::lang_start. - A frame for
myapp::main. - A frame for
myapp::count_primesthat covers almost the entire width. - Above it, iterator and closure frames from the
filterandallcalls, andmyapp::is_primeor its closure.
Compiler inlining may merge some of these. With optimizations on, is_prime can be inlined into count_primes, so you might see the work attributed to a closure or to count_primes itself rather than to a separate is_prime box. The source lines from debug info help you tell what the box really represents. Hover over a box to see its name and sample count, click to zoom into it, and use the search box (top right) to highlight every frame matching a name.
The plateau at the top, the widest box with nothing above it, is the code that was on the CPU when most samples fired. Here that is the n % d loop. You have found your hotspot. The next chapter covers how to read such graphs in detail.
Common problems
- Names look like
_ZN4core4iter.... These are mangled symbols. Most flamegraph tools demangle Rust names automatically. If yours do not, update the tool or pipe the output throughrustfilt. - Most boxes are
[unknown]. Debug info is missing or stacks could not be unwound. Check thatdebug = trueis set under[profile.release]and that you are profiling the release binary. - The graph has only a few samples and looks sparse. The program finished too quickly. Increase the workload, for example by raising
100_000, or run the profiled code in a loop. - The build seems to ignore your change. Cargo reuses build artifacts. Run
cargo clean -p myappif you suspect a stale binary. - The SVG appears in the wrong place. The file is written to the directory where you ran the command, not the project's
targetdirectory. Use--outputto control the path.
Exercise
You run cargo flamegraph --bin myapp on Linux and perf fails with a permission error. Name two ways to get the profile, and give one drawback of each.
Show answer
Lower kernel.perf_event_paranoid with sudo sysctl -w kernel.perf_event_paranoid=1, which lasts until reboot but exposes more performance data to all local users. Or run cargo flamegraph --root --bin myapp, which uses sudo for the run but may leave flamegraph.svg owned by root.
Exercise
Why do you add debug = true under [profile.release] instead of profiling the default dev profile?
Show answer
Debug info lets the profiler map samples to function names and source lines, while the release profile keeps the optimizations that make the program run like the shipped build. The dev profile is unoptimized, so its hotspots can differ from those in a real release binary.
Exercise
Run cargo flamegraph --bin myapp on the prime counter. Which function or closure forms the widest box with nothing on top of it, and what does its width tell you?
Show answer
The widest top box is the trial-division loop, shown as is_prime, its closure, or count_primes if inlining merged them. Its width is the fraction of samples taken while that code was running, so it is roughly the fraction of CPU time spent there. For this program it should be most of the graph.