Sub topic 3
Anatomy of a flamegraph
This chapter explains how to read a flamegraph as a data structure. It assumes you know what a call stack is and that a sampling profiler records stacks at a fixed rate, both covered earlier in this tutorial. You don't need to have generated a flamegraph yet. The next chapters cover building and recording.
From samples to a picture
A flamegraph is a rendering of many stack samples merged into one tree. Each sample is a list of function names from the outermost caller to the function that was running when the sample was taken. The renderer works in three steps:
- It writes each sample as one line, with frames joined by semicolons. This is the folded format.
- It counts identical lines.
- It merges lines that share a prefix into a tree and draws the tree.
Here is the folded form of a profile of the prime-counting program used in this tutorial:
main;count_primes;is_prime 870
main;count_primes 30
main;print 10The number at the end of each line is how many samples had exactly that stack. The first line says that in 870 samples, is_prime was running, called by count_primes, called by main. The second line says that in 30 samples, count_primes itself was the function executing, with no deeper call active.
The axes
| Axis | What it encodes | What it does not encode |
|---|---|---|
| Vertical | Stack depth. The root is at the bottom, and each box sits on its caller. | Time. A tall tower is a deep call chain, not a slow one. |
| Horizontal | Share of samples. A box's width is the number of samples in which that frame appeared on the stack. | Chronological order. Left to right is not "earlier to later". |
Most standard renderers sort sibling boxes alphabetically. This makes identical stacks line up and merge. It also means the left-right position of a box carries no meaning. Only the width does.
Width is a proportion of all samples. A box that spans half the graph was on the stack in about half the samples. If the sampler ran at 99 Hz for 10 seconds, that is about 495 samples, or about 5 seconds of CPU time. The estimate is only as good as the sample count, so graphs built from a few hundred samples are noisy.
The tree behind the picture
The three folded lines above merge into this tree. The numbers are sample counts.
In the flamegraph, main is a full-width box at the bottom. count_primes sits on it and covers 900 of 910 columns' worth of width. print is a sliver next to it. is_prime sits on top of count_primes and is almost as wide.
Total time and self time
Every box has two numbers, and the picture shows them differently.
- Total time is the number of samples in which the function appears anywhere on the stack. It includes time spent in everything the function called. It equals the box's width.
- Self time is the number of samples in which the function was the innermost frame, so it was the code actually running. In the picture it is the part of the box's width that has nothing stacked above it.
Here count_primes has a total of 900 and a self time of 30. The other 870 samples belong to is_prime. main has a total of 910 and a self time of 0.
The rule for finding where time goes follows from this. A wide box is not necessarily a problem, because it may only be a caller whose callees do the work. Look at the top edges of the graph, where boxes have exposed width with nothing above them. Those flat tops, often called plateaus, are where the CPU was executing.
Computing the numbers yourself
The following program reads folded stacks and computes total and self counts the same way a renderer does. It counts each function once per stack for the total, so recursive functions are not counted twice.
use std::collections::HashMap;
fn main() {
let folded = "main;count_primes;is_prime 870\nmain;count_primes 30\nmain;print 10\n";
let mut total: HashMap<String, u64> = HashMap::new();
let mut own: HashMap<String, u64> = HashMap::new();
let mut all: u64 = 0;
for line in folded.lines() {
let (stack, count) = line.rsplit_once(' ').expect("line needs a count");
let count: u64 = count.parse().expect("count must be a number");
all += count;
let frames: Vec<&str> = stack.split(';').collect();
let leaf = frames.last().expect("empty stack");
*own.entry(leaf.to_string()).or_default() += count;
let mut seen: Vec<&str> = Vec::new();
for f in frames.iter().copied() {
if !seen.contains(&f) {
seen.push(f);
*total.entry(f.to_string()).or_default() += count;
}
}
}
let mut rows: Vec<(&String, u64)> = total.iter().map(|(k, v)| (k, *v)).collect();
rows.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
println!("{:<14} {:>6} {:>6} {:>7}", "function", "total", "self", "total%");
for (name, t) in rows {
let s = own.get(name).copied().unwrap_or(0);
let pct = t as f64 * 100.0 / all as f64;
println!("{:<14} {:>6} {:>6} {:>6.1}%", name, t, s, pct);
}
}It prints:
function total self total%
main 910 0 100.0%
count_primes 900 30 98.9%
is_prime 870 870 95.6%
print 10 10 1.1%The is_prime row shows total equal to self. Nothing sits above it in the graph, so it is a plateau, and it is the place to start looking.
Merging rules and their consequences
Boxes merge only when the whole path from the root matches. This has practical effects:
- One function, many boxes. If
is_primeis called from bothcount_primesandverify, it appears as two separate boxes under different parents. The cost ofis_primeis the sum of the widths of all its boxes. Most flamegraph viewers have a search function that highlights every box matching a name and reports the combined percentage. Use it before concluding that a function is cheap. - Recursion makes towers. A function that calls itself ten levels deep draws ten stacked boxes with the same name. Each box's width is the samples that reached at least that depth.
- Different call paths to the same leaf are not merged. This is why the graph shows who called the hot code, which a flat list of functions hides.
Colors, labels and what is omitted
In the usual hot-to-cold palette, color is chosen for visual separation and carries no information about cost. Some tools color by crate or module, or by whether the frame is user code, library code or kernel code. Check the tool's documentation before reading meaning into a color.
Labels are truncated to fit the box width. Hover text, or the status line in the SVG, shows the full function name, sample count and percentage. Boxes narrower than a threshold are dropped from the drawing, which is typically 0.1 percent of samples. A graph with many thin slivers can therefore hide a long tail of small costs that, added together, matter.
Variants
- Icicle graph. The same data drawn upside down, with the root at the top. The reading rules are identical.
- Reversed (inverted) graph. The leaf function is the base, and callers are stacked above it. This merges all samples by the function that was running, so it shows self time per function directly. It is useful when a hot function is called from many places.
- Differential graph. Shows the change between two profiles. It is covered in a later chapter.
Limits of the picture
A flamegraph is a statistical estimate, and a few conditions affect how far to trust it:
- Few samples. With 100 samples, a box with 3 samples could plausibly be 1 or 6 in another run. Record for longer or raise the frequency before drawing conclusions from narrow boxes.
- Broken stacks. Frames labeled
[unknown], or a graph whose roots are notmain, mean the unwinder failed. Stack unwinding is a later chapter. - CPU time only. The default graph counts samples taken while a thread was on the CPU. A thread blocked on a lock or a disk read does not appear.
Exercise
A folded profile has these lines: "main;parse;tokenize 400", "main;parse 100", "main;run;tokenize 300", "main;run 200". There are 1000 samples in total. (a) What is the total time of tokenize, and what is its share of all samples? (b) What is the self time of parse? (c) In the flamegraph, how many boxes are labeled tokenize, and why does that matter when judging its cost?
Show answer
(a) tokenize appears in 400 + 300 = 700 samples, which is 70 percent of the total. (b) parse has a self time of 100, because only the line "main;parse 100" ends in parse. (c) There are two tokenize boxes, one under parse (width 400) and one under run (width 300), since their paths from the root differ. Each box alone looks smaller than the true cost, so use the viewer's search to see the combined 70 percent.