Sub topic 12
Comparing Before and After with Differential Flamegraphs
A single flamegraph tells you where time goes. After you change the code, you need to know what the change did. You could read two flamegraphs side by side and compare box widths by eye, but that is slow and easy to get wrong. A differential flamegraph does the comparison for you. It draws one graph and colors each frame by how much it grew or shrank between two profiles.
This chapter assumes you can already record a profile with perf and fold it with inferno-collapse-perf, as covered in the pipeline chapter. It also assumes you have read the chapter on checking optimizations with benchmarks.
What a differential flamegraph shows
A differential flamegraph is built from two profiles of the same program, called before and after. Each unique stack gets two sample counts, one from each profile. The graph is then drawn with these rules:
- The shape and widths come from the after profile.
- The color shows the change in that stack's sample count. Red means the stack got more samples. Blue means it got fewer. White or pale means little change.
- A deeper shade means a larger change.
Because widths come from the after profile, the graph answers the question "what does my program look like now, and which parts of it changed?" The colors show where the change is.
The inferno tools implement this in two steps. inferno-diff-folded reads two folded stack files and merges them into one file with a count column for each. inferno-flamegraph detects the two-column format and renders the colored SVG.
The folded diff format
A normal folded file has one line per unique stack:
main;count_primes;is_prime 9210inferno-diff-folded outputs the stack followed by two counts, before and after:
main;count_primes;is_prime 9210 41A stack that exists in only one profile gets a zero in the other column. This format is plain text, so you can sort and filter it with ordinary tools. That is useful when the colors are hard to judge.
Running the comparison
Record both profiles with identical settings. Then fold each one and diff them. The commands below reuse the prime-counting example from earlier chapters.
perf script | inferno-collapse-perf > before.folded
# ...rebuild with the fix, record again...
perf script | inferno-collapse-perf > after.folded
inferno-diff-folded before.folded after.folded | inferno-flamegraph > diff.svgIn the first chapter's example, the original is_prime divides by every number below n. The fix stops at the square root:
fn is_prime(n: u64) -> bool {
if n < 2 {
return false;
}
(2..).take_while(|d| d * d <= n).all(|d| n % d != 0)
}Open diff.svg in a browser. The is_prime frame is mostly gone from the after profile, so the graph is dominated by other work such as the runtime startup and count_primes itself. The surviving is_prime frames are blue because their sample counts dropped.
Why removed code seems to vanish
The graph is drawn from the after profile. A stack that exists only in the before profile has zero width in the after profile, so it does not appear at all. The biggest win in a change can therefore be invisible in the picture.
There are two ways to see removals:
- Swap the arguments, so the old profile is drawn with the new one as the baseline:
inferno-diff-folded after.folded before.folded | inferno-flamegraph > reverse.svg. In that graph, widths come from the old code, and the colors show what the fix removed. - Pass
--negatetoinferno-flamegraphif you want the reversed graph to keep red for "worse" and blue for "better" from the viewpoint of the original direction.
Reading both the forward and the reverse graph gives the full picture. The forward graph shows what remains and what grew. The reverse graph shows what was removed.
Normalizing when run lengths differ
Raw counts are only comparable when both runs collected a similar total number of samples. That is true when the program does the same work for the same time. After a successful optimization, the total number of samples drops, because the program finishes sooner. In that case the raw counts are what you want: a drop in samples is a drop in CPU time.
Sometimes the two profiles are not comparable this way. The workload may have run for different lengths of time, or you may care about the share of time a function takes, not its absolute cost. In that case use the normalize option, which scales the first profile's counts so both profiles have the same total:
inferno-diff-folded --normalize before.folded after.folded | inferno-flamegraph > diff-normalized.svgWith normalization, a frame is red if it takes a larger fraction of the run than before. This is a different question from "did it get slower". A function can be red after normalization even though its absolute cost did not change, simply because other functions got faster.
| Option | Colors answer | Use it when |
|---|---|---|
| No normalization | Did this stack get more or fewer samples? | The same fixed workload ran in both profiles. |
| `--normalize` | Did this stack take a larger or smaller share of the run? | Run lengths or workload sizes differ. |
Making the comparison trustworthy
A differential graph is only as good as the match between the two profiles. Noise and mismatches show up as colors that look like real changes.
- Keep everything but the code the same. Use the same workload, input size, sampling frequency (for example
-F 99), build profile, andRUSTFLAGS. If you add frame pointers for one run, add them for the other. - Record on a quiet machine. Other processes change cache behavior and CPU frequency, which shifts the samples.
- Expect sampling noise. Small colored frames with few samples can change by chance. Only trust changes in frames that have many samples. Record more than once if a result looks surprising.
- Watch for renamed frames. If a function appears fully blue in one place and fully red in another, the profiler may be labeling the same code differently in the two builds. Causes include changed inlining, different generic instantiations, or addresses in names.
inferno-diff-folded --strip-hexremoves hexadecimal addresses from names so the stacks match.
Finding the biggest changes in text
Colors help you spot a change, but the exact numbers are in the folded diff. This command lists the ten stacks that lost the most samples. It reads the last two fields of each line, so function names that contain spaces do not break it.
inferno-diff-folded before.folded after.folded \
| awk '{ print ($NF - $(NF-1)), $0 }' \
| sort -n \
| head -n 10The first column is the change in samples (after minus before). Negative numbers are improvements. To list the biggest regressions, use sort -nr instead of sort -n.
Note that each line is a full stack, so a frame near the root appears in many lines. The leaf frame of a stack holds its self time. When you want to know which function is responsible, look at the last frame in the stack.
A workflow for checking a fix
- Record and fold a baseline profile, and save it. Keep the exact command and workload.
- Make one change.
- Record and fold again with identical settings.
- Generate the forward and reverse differential graphs.
- Check that the frames you expected to shrink are blue, and look for unexpected red frames elsewhere.
- Confirm the speedup with a benchmark. A differential flamegraph shows where samples moved. It does not give a trustworthy timing. Use a benchmark harness for the final number.
Step 5 is where differential graphs earn their keep. An optimization can move cost somewhere else, for example by replacing a computation with allocation. A red frame in an unexpected place is how you catch that.
Limits
- The graph shows CPU samples only. A change that reduces waiting for I/O or locks will not show up, because those samples are not collected by a CPU profile.
- Colors show change but not cause. A red frame tells you where to look, not why.
- Two profiles of a program with a random or input-dependent workload may differ for reasons unrelated to your change. Fix the inputs.
Exercise
You optimize a function and diff the profiles. The forward differential flamegraph shows no trace of the old slow function, and you suspect your tool is hiding something. What explains this, and what command shows what the fix removed?
Show answer
The forward graph takes its widths from the after profile. A stack that exists only in the before profile has zero samples there, so it has no width and is not drawn. Swap the arguments to draw from the before profile: inferno-diff-folded after.folded before.folded | inferno-flamegraph > reverse.svg. The reverse graph is sized by the old code, and its colors show the frames that lost samples.
Exercise
Your before run processed 1,000,000 items and your after run processed 100,000 items. Should you use --normalize when diffing, and what question do the colors answer when you do?
Show answer
Yes, because the runs have different total sample counts and raw counts would show nearly everything as blue. With --normalize, the first profile is scaled to the same total as the second, so the colors show whether a stack takes a larger or smaller share of the run, not whether it uses more or fewer absolute samples.