Sub topic 7
Reading the graph: finding hotspots
This chapter assumes you can already produce a flamegraph, either with cargo flamegraph or with the perf and inferno pipeline. It also assumes you know what a call stack is. Here you learn to read the picture and decide which function to change first.
What each part of the picture means
A flamegraph is built from sampled stacks. The profiler records the full call stack many times per second, and the tool merges identical stack prefixes into boxes. Three rules cover most of the reading.
- Width is samples. A box that spans 40% of the width appeared in 40% of the samples. For a CPU profile, that is roughly 40% of the CPU time.
- Vertical position is call depth. The bottom box is the outermost frame, usually the thread entry or
main. Each box sits on its caller, and the boxes above it are the functions it called. - Left-to-right order is not time. Boxes at the same level are sorted alphabetically by name so that identical stacks merge. A box on the left did not run before a box on the right.
Colors are also decoration in the default palette. Warm shades are chosen at random, so a red box is not "worse" than a yellow one. Some tools color by crate or by user code versus library code, so check the legend before you assume a color means anything.
Self time and total time
Every box has two numbers.
- Total time is the width of the box. It includes everything the function called.
- Self time is the part of the box whose top edge is not covered by another box. It is time spent in the function's own instructions.
A main frame usually has near-100% total time and near-0% self time. That tells you nothing, because everything runs under main. The useful question is where self time is large. In a flamegraph, self time shows up as a flat, wide top edge with nothing stacked above it. This flat top is called a plateau.
You can compute both numbers yourself from a folded stack file. That is the intermediate format that inferno-collapse-perf writes. Each line is a semicolon-separated stack followed by a sample count. The script below uses a small made-up sample for the slow prime counter from the earlier chapters.
from collections import Counter
folded = """\
myapp::main;myapp::count_primes;myapp::is_prime 940
myapp::main;myapp::count_primes 40
myapp::main;std::io::stdio::_print 20
"""
self_samples = Counter()
total_samples = Counter()
total = 0
for line in folded.strip().splitlines():
stack, count = line.rsplit(" ", 1)
count = int(count)
frames = stack.split(";")
total += count
self_samples[frames[-1]] += count
for frame in set(frames): # count a recursive frame once per sample
total_samples[frame] += count
for frame, samples in total_samples.most_common():
print(
f"{frame:30} total {samples / total:6.1%} "
f"self {self_samples[frame] / total:6.1%}"
)It prints:
myapp::main total 100.0% self 0.0%
myapp::count_primes total 98.0% self 4.0%
myapp::is_prime total 94.0% self 94.0%
std::io::stdio::_print total 2.0% self 2.0%count_primes has 98% total time but only 4% self time. Its width comes almost entirely from is_prime. is_prime has 94% self time, so it is the hotspot. This is the pattern you look for in the real SVG.
Shapes you will see
Most hotspots fall into a few recognizable shapes.
| Shape | What it means | Typical response |
|---|---|---|
| Wide plateau with an exposed top | One function burns CPU in its own code | Optimize the algorithm or the inner loop |
| Wide box with one wide child | The time is in the callee, and the parent only forwards it | Descend and look at the child |
| Wide box with many narrow children | Cost is spread over many callees | Look for what they share, such as allocation or hashing |
| Tall, narrow tower | Deep call chain with little time | Usually harmless, so ignore it unless the tower is wide |
| Same function in many places | One routine called from many sites | Merge the cost mentally, or use search |
| Wide `alloc`, `memcpy` or `drop` boxes | Allocation or copying overhead | Reuse buffers, borrow instead of cloning, pre-size collections |
Height is the one thing beginners misread most often. A tall tower means deep recursion or layered abstractions. It says nothing about cost unless it is also wide.
A procedure for finding the hotspot
- Check the total sample count. The SVG shows the sample count for the root box on hover. Hundreds of samples can be noisy. Thousands are usually enough to trust boxes above a few percent.
- Start at the widest boxes in your own code. Standard library and runtime frames often sit at the bottom. Skip past them to the first frames named after your crate.
- Climb from the root along the widest path. At each level, ask whether the box's top is exposed. If it is, you have found self time. If it is covered, move to the widest child.
- Look for plateaus anywhere. The widest path is not always where the hotspot is. A small plateau in a function that runs from 20 different callers can add up to more than one large plateau.
- Use search. Click the search button in the SVG, or press Ctrl+F, and enter a function name or regex. Matching boxes turn purple, and the page shows what share of all samples contain a match. This is the fastest way to measure functions that appear in several places, such as
memcpyorHashMap. - Click to zoom. Clicking a box makes it the new full-width root, which makes narrow children readable. Click the reset link to zoom back out.
- Map the box to source. With
debug = truein the release profile, the hover text names the function, and tools such asperf annotatecan attribute samples to source lines. Open that function and read the loop.
For the slow prime counter, a real flamegraph shows count_primes near the bottom, with is_prime or a closure inside it dominating the top. Frames from the iterator adapters (all, try_fold, filter) may appear between them. That is normal. The plateau is the trial-division loop, which matches the (2..n).all(...) line.
Common reading mistakes
- Treating the x-axis as a timeline. Alphabetical order means two boxes side by side are unrelated in time. If you need a timeline, use a tracing tool, not a flamegraph.
- Chasing the widest box with no exposed top. A wide parent is only a route to the cause. Optimizing the parent's own code changes little.
- Ignoring many thin boxes. Ten 3% boxes that all call the same allocator add up to 30%. Use search to total them.
- Trusting very small boxes. At 99 Hz, a 10-second run gives about 990 samples. A box with 5 samples is within noise. Record longer or raise the sampling frequency before you read anything into it.
- Reading a profile of the wrong workload. The graph is accurate for the program you ran. If the input was tiny or unrealistic, the hotspot may not matter in production.
- Forgetting that inlining merges frames. A small function may not appear as its own box because the compiler copied it into its caller. Its cost is then attributed to the caller. The next chapter covers this.
- Reading a CPU graph as wall-clock time. Time spent waiting on a lock, disk or network does not appear in an on-CPU profile. A program that is slow but has a thin, flat graph is probably waiting.
Recording what you found
Before you change code, write down the finding in a form you can check later:
- the function and source line of the plateau,
- its share of total samples, and its self share if different,
- the workload and sampling frequency used,
- your prediction of the best-case speedup.
For the prime counter, that note would read: "is_prime trial-division loop, 94% self time, input 100_000, 99 Hz, ceiling roughly 16x." The ceiling comes from 1/(1 - 0.94), which is about 16.7. Later chapters use this note to verify the fix with a benchmark and a differential flamegraph.
Exercise
A flamegraph has a box parse_config that is 50% of the width, with a single child read_file that is 48% wide. Under read_file is a box memcpy that is 45% wide with nothing above it. Which function has the highest self time, and what is the maximum overall speedup you could get by making it free?
Show answer
memcpy has the highest self time, about 45%, because it is the only box with an exposed top. parse_config has about 2% self time and read_file about 3%. Making memcpy free removes at most 45% of the samples, so the best-case speedup is 1/(1 - 0.45), about 1.8x. A better fix is usually to avoid the copy at its caller, since memcpy itself cannot be made faster.
Exercise
At 99 Hz, you profile a program for 5 seconds and see a function box covering 8 samples. Should you optimize it? Why or why not?
Show answer
Not yet. The run produced about 495 samples, so 8 samples is about 1.6%. At that count the share is within sampling noise, and even a perfect fix would give under 2% improvement. Record a longer run or a higher frequency before drawing conclusions.