Profiling with flamegraph
Learn what a flame graph shows, how cargo flamegraph turns perf samples into one picture of where CPU time goes, and what to do when perf is not available
Profiling means measuring where a program spends its time instead of guessing. A flame graph is one picture of that measurement: a stack of coloured bars, where the width of a bar shows how much of the total time was spent in that function, and the bars above it show what called it. The cargo-flamegraph tool, from the flamegraph crate, runs a Rust binary under the Linux profiler perf, collects samples of what the program was doing, and draws the graph as an SVG file. This page explains how to read that picture, how to produce it, and what was actually verified on the machine used to check this page, including the part that did not work.
Where This Fits
A slow server invites guessing. The database is blamed, then the JSON parsing, then the framework, usually in that order, and usually wrongly. A profiler replaces the guessing with a measurement: run the program, sample what it is doing many times a second, and count where the samples land. The function with the most samples is where the time goes. A flame graph is the readable form of that count. It does not fix anything by itself. It tells you where fixing something would matter.
Think of a time-lapse photo of a kitchen during dinner service. The photo does not show any one moment. It shows where the cooks stood most often. If one cook spent half the evening at the sink, the sink is the bottleneck, whatever anyone guessed beforehand. The flame graph is that photo, for functions instead of cooks.
The Smallest Working Version
Profiling needs something to profile. A small program with one obviously slow function is enough to learn the tool on. This one parses the same JSON string a hundred thousand times and times the whole run.
[package]
name = "parse-bench"
version = "0.1.0"
edition = "2021"
[dependencies]
serde_json = "1"
use std::time::Instant;
fn parse_book(input: &str) -> usize {
let value: serde_json::Value = serde_json::from_str(input).unwrap();
value.as_object().map(|o| o.len()).unwrap_or(0)
}
fn main() {
let input = r#"{"id": 1, "title": "The Rust Book", "author": "The Rust Team", "tags": ["rust", "systems", "programming"]}"#;
let start = Instant::now();
let mut total = 0usize;
let runs = 100_000;
for _ in 0..runs {
total += parse_book(input);
}
let elapsed = start.elapsed();
println!("{runs} parses in {:?} ({:?} per parse, checksum {total})", elapsed, elapsed / runs);
}
Run it normally first, so there is a baseline number to compare against later:
cargo run --release
On the machine used to check this page, the debug build of the same program printed:
100000 parses in 3.936692305s (39.366us per parse, checksum 400000)
Microseconds Spelled Out:
The real terminal prints 39.366 followed by the Greek letter mu, which means microseconds. This page writes 39.366us instead, because the docs use plain ASCII characters only and the Greek letter is not one of them. The number is the same.
That is about 39 microseconds per parse in a debug build, which is unoptimised. A release build would be faster, and the exact number depends on the machine. The number itself is not the point. The point is that the program does one thing, repeatedly, so a profiler has something clear to find.
Install the tool:
cargo install flamegraph
The crate is named flamegraph, and installing it provides the cargo-flamegraph subcommand. The version installed for this page was 0.6.15. Check it is there:
cargo flamegraph --help
The help lists the options the tool accepts, including --dev to profile a debug build, --profile to pick a named profile, --bin to pick which binary to run, and --test and --bench to profile a test or a benchmark instead of the main binary. Then run it:
cargo flamegraph --bin parse-bench
The tool builds the binary in release mode, runs it under perf record, converts the samples into a flame graph, and writes flamegraph.svg in the project directory. Open that file in a browser. The picture is the profile.
Working Setup:
If cargo flamegraph --bin parse-bench finishes and flamegraph.svg appears in the project directory, profiling works on the machine. Opening the SVG in a browser should show a stack of bars with function names on them. If the command fails, the next section is the one that matters, because it failed here too.
What Happened on This Machine
This section is honest about a failure, because the failure is the most useful part of the page for anyone on a similar machine. The machine used to check this page runs a Linux kernel, version 7.0.0-44-generic, inside a virtual machine. The perf tool is the piece cargo-flamegraph needs on Linux, and perf was not usable there. Running it printed:
WARNING: perf not found for kernel 7.0.0-44
You may need to install the following packages for this specific kernel:
linux-tools-7.0.0-44-generic
linux-cloud-tools-7.0.0-44-generic
No package with that name exists in the package lists for this machine. Installing the generic tools package, linux-tools-generic, did install a perf binary, but it was built for a different kernel version, 6.8, and it printed the same warning and refused to run. The running kernel and the available tools do not match, and there is no package that matches the running kernel.
Running the tool itself confirmed the failure end to end:
cargo flamegraph --dev --bin parse-bench
The output ended with:
failed to sample program, exited with code: Some(2)
No flamegraph.svg was produced, and no perf.data file was left behind. The tool is installed and its help works. The sampling step fails because perf cannot run on this kernel. That means no flame graph was produced while checking this page, and no picture in this page comes from a real run on this machine. The rest of the page explains how to read the graph and how to get one on a machine where perf works, and it labels which parts are documented behaviour and which parts were measured here.
No Flame Graph Was Produced Here:
Do not trust any flame graph claimed to come from this machine. The perf tool cannot run on kernel 7.0.0-44-generic here, cargo flamegraph exits without sampling, and no SVG was generated. The reading guide below describes the format as documented, not a picture from this run. On a machine where perf works, the same commands produce a real graph.
How to Read a Flame Graph
A flame graph is read from the bottom up. The bottom bar is the whole program, and its width is all of the sampled time. Each bar above it is a function called by the bar below it. A bar's width is the share of total time spent in that function and everything it called. A wide bar near the bottom is a function that owns a large share of the time. A tall stack is a deep call chain. The colours mean nothing by themselves; they are chosen to tell neighbouring bars apart, not to mark hot and cold.
Three shapes are worth recognising. A wide flat plateau, a bar that is wide and has few children, is time spent inside that one function, doing its own work. That is the shape a slow JSON parser makes: one wide bar for the parsing function, with thin slivers above it for helpers. A tall thin tower is a deep call chain that costs little by itself but adds up through depth, often a sign of recursion or layers of wrappers. Many small bars side by side under one parent is time spread across many small functions, where no single fix helps much and the parent is the thing to think about.
The classic mistake is to read the top of the graph as the problem. The top bars are the leaves, the functions that were actually running when the sample was taken. They are where the time is, but they are not always where the fix is. A leaf that parses JSON is slow because it parses JSON. The fix might be to call it less often, which is a change in the caller below it, not in the leaf. Read the graph bottom up, find the wide bars, and ask which of them should not be there at all.
How the Tool Works Underneath
Three programs cooperate to make the picture. perf record is the Linux profiler. It interrupts the running program many times a second, by default 99 times a second, and each time it writes down the stack of function calls the program was in. The number 99 is deliberate: sampling at exactly 100 times a second could line up with a program that does something exactly 100 times a second and sample the same moment every time, which would skew the picture.
cargo-flamegraph is the wrapper. It builds the binary, runs it under perf record, and then feeds the recorded samples to the inferno crate, which is the Rust implementation of the flame graph drawing. Inferno collapses identical stacks, counts them, and draws the SVG. The SVG is a normal image file that opens in a browser, and it is searchable: typing a function name in the browser's find highlights every bar with that name.
Two details matter for Rust programs in particular. The first is debug symbols. A release build without debug information gives the profiler addresses instead of function names, and the graph becomes unreadable. cargo-flamegraph handles this by building with debug information kept, so the graph has names. The second is inlining. The compiler can merge a small function into its caller, and the profiler then sees the caller's name instead of the small function's name. That is not an error. It means the small function costs nothing on its own, which is itself information.
Profiling the Axum Server Instead of a Small Program
A small program is the place to learn the tool. A server is the place to use it. The command shape is the same, with the binary being the server:
cargo flamegraph --bin weather-api
The server runs under the profiler until it is stopped with Ctrl+C, and the graph covers the whole run, including startup and every request served in between. To profile one kind of request, start the server under the tool, send the requests to exercise, then stop the server. The samples from the requests and the samples from idle waiting are mixed together in the graph, so a server that mostly waits will show a wide bar for waiting. That is correct and uninteresting. The interesting part is the share of the busy time, which is the work done while answering requests.
Two habits make server profiles useful. The first is to send load while profiling, so the graph measures the request path rather than the idle loop. A load tool such as wrk can generate that load, and the benchmarking topic covers it. The second is to profile a release build, because a debug build spends its time in places a release build optimises away, and the graph would then describe the debug build, not the server that actually runs.
When perf Is Not Available
On a machine where perf cannot run, the tool cannot sample, and no flag changes that. Three fallbacks exist, in order of usefulness. The first is to profile on a machine where perf works, such as a development laptop or a server with a matching kernel tools package, and to treat that profile as representative of the same code. The second is to measure with a timing harness, the way the small program at the top of this page does: wrap the suspect code in a loop, time it with Instant, and print the per-call cost. That gives one number for one function, not a whole picture, but the number is real and it answers the question of whether that function is slow. The harness on this machine measured about 39 microseconds per JSON parse in a debug build, which is a real measurement of a real function, even though it is not a flame graph.
The third fallback is the flamegraph crate's own library form, which can generate a flame graph from data collected another way, and the pprof style samplers that some Rust crates provide. Those are heavier setups, and they belong to a profiling deep dive rather than this page. The honest summary is that without a working sampler there is no flame graph, and a timing harness is the fallback that still tells the truth.
A Debug Profile Describes the Debug Build:
Profiling with --dev is convenient, because the build is fast, but the numbers describe unoptimised code. A function that looks slow in a debug profile may vanish in a release profile, because the optimiser removed it or inlined it. Use --dev to learn the tool and to find gross problems. Use the default release build for any number that will drive a decision.
What the Flow Looks Like
cargo flamegraph --bin weather-api
|
v
Build the binary with debug information
|
v
perf record samples the call stack 99 times a second
|
v
Program runs and serves requests, then stops
|
v
inferno collapses identical stacks and counts them
|
v
flamegraph.svg is written
|
v
Browser shows the graph, bottom is the whole program,
width is share of time, top is the running function
Every step after the build depends on perf. If perf cannot run, the chain stops at the sampling step, which is exactly what happened on the machine used to check this page.
Testing It
A flame graph is not something a unit test asserts on. What a test can do is keep the slow function honest: assert that the function under investigation still returns the right answer, so a later optimisation does not change behaviour while chasing speed.
#[test]
fn parse_book_counts_fields() {
let input = r#"{"id": 1, "title": "The Rust Book", "author": "The Rust Team"}"#;
let value: serde_json::Value = serde_json::from_str(input).unwrap();
assert_eq!(value.as_object().unwrap().len(), 3);
}
The useful check around profiling is a manual one, and it belongs in the workflow, not in the test suite: run the timing harness before a change, run it after, and compare the numbers on the same machine and the same build profile. A flame graph shows where time goes. The harness shows whether a change moved the number. Both are needed, and neither replaces the other.
Common Beginner Mistakes
Profiling a debug build and optimising the result
A debug build spends time on bounds checks and unoptimised code that a release build removes. Optimising based on a debug profile can mean fixing a function that costs nothing in production. The fix is to profile the release build whenever the result will drive a decision, and to treat a debug profile as a sketch.
Reading the top of the graph as the problem
The leaves are where time is spent, but the fix is often in a caller that calls the leaf too often, or with too much data. A wide leaf for JSON parsing might be fixed by caching the parsed result, which is a change in the caller, or by sending less JSON, which is a change further down the stack. Read bottom up and ask what should not be there at all.
Sampling too briefly
A one second sample of a server that handles one request a second is one request, and the graph describes that request, not the server. Profile for long enough to cover the behaviour being investigated, with load running, so the samples represent the workload. A short sample is a photograph of a moment, not a measurement of the system.
Chasing a wide bar that is supposed to be wide
A server that waits for the network will show a wide bar for waiting. A program that hashes passwords will show a wide bar for hashing. Those bars are wide because the work is the work. The question is never whether a bar is wide. It is whether the work it represents should exist at all, or should cost that much. A wide bar for JSON parsing on a route that returns JSON is expected. The same bar on a route that should return a cached string is the bug.
Final Complete Example
Here is everything from the page put together: the timing harness, the commands to install and run the tool, and the honest note about the machine where it was checked.
use std::time::Instant;
fn parse_book(input: &str) -> usize {
let value: serde_json::Value = serde_json::from_str(input).unwrap();
value.as_object().map(|o| o.len()).unwrap_or(0)
}
fn main() {
let input = r#"{"id": 1, "title": "The Rust Book", "author": "The Rust Team", "tags": ["rust", "systems", "programming"]}"#;
let start = Instant::now();
let mut total = 0usize;
let runs = 100_000;
for _ in 0..runs {
total += parse_book(input);
}
let elapsed = start.elapsed();
println!("{runs} parses in {:?} ({:?} per parse, checksum {total})", elapsed, elapsed / runs);
}
cargo install flamegraph
cargo flamegraph --help
cargo flamegraph --bin parse-bench
The first command installs the tool, version 0.6.15 as checked here. The second prints the options, including --dev, --profile, --bin, --test, and --bench. The third builds the binary, samples it with perf, and writes flamegraph.svg. On the machine used to check this page, the third command failed at the sampling step with failed to sample program, exited with code: Some(2), because perf cannot run on kernel 7.0.0-44-generic and no matching tools package exists. The timing harness still ran and measured about 39 microseconds per parse in a debug build.
Summary
The single most important insight is that a flame graph answers one question, where does the time go, and it answers it with a measurement rather than an opinion. The width of a bar is a count of samples, not a guess about importance, and reading the graph bottom up finds the work that owns the time. The tool chain is three parts, perf to sample, cargo-flamegraph to drive it, and inferno to draw it, and the chain is only as strong as perf on the machine in question.
The decision framework follows from that. When the server is slow and the cause is unknown, profile before optimising, read the graph bottom up, and fix the wide bar that should not be there. When perf cannot run, say so plainly, measure the suspect function with a timing harness, and profile on a machine where the sampler works. A missing graph is a fact about the machine, not a reason to guess.