Sub topic 1
Call stacks: the raw material of a profile
A flamegraph looks like a picture of time, but it is built from something simpler: lists of function names, each list called a call stack. This chapter explains what a call stack is, how to read one, what information it holds, and why a profiler collects thousands of them. The later chapters on sampling and flamegraph anatomy rely on this material.
Prerequisites
This chapter assumes you can:
- Write and run a small Rust program with
cargo run, and know whatcargo build --releasedoes. - Use a terminal comfortably.
- Read a function call such as
a()callingb()and follow which function is running.
You do not need any profiling tools installed yet. The only code here runs with the standard library.
What a call stack is
When a program calls a function, the CPU must remember where to return when that function finishes. It also needs room for the function's local variables. Both live in a region of memory called the call stack. Each function call adds one block to the stack, called a stack frame. When the function returns, its frame is removed.
A frame typically holds:
- The return address, which is where execution continues in the caller.
- Local variables and temporaries that did not fit in CPU registers.
- Saved register values the function must restore before returning.
The stack grows with each nested call and shrinks with each return. At any moment, the frames on the stack describe a chain: the function running now, the function that called it, the function that called that one, and so on up to the program's entry point.
Take the program from this tutorial's running example:
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));
}While the all loop inside is_prime runs, the stack holds (from outermost to innermost) main, count_primes, and is_prime. A snapshot of that chain is a stack trace, or just a stack.
Reading a stack trace
Stacks are written in two common orders. Debuggers and panic messages usually put the innermost function (the leaf) first and the entry point last. Flamegraph tools, and the text format they use, put the entry point first and the leaf last, separated by semicolons:
main;count_primes;is_primeBoth describe the same chain. When you read a tool's output, check which end is which before you draw conclusions.
The terms are used like this:
- Leaf frame: the function that was executing when the snapshot was taken.
- Caller and callee: in
count_primescallingis_prime, the first is the caller and the second is the callee. - Depth: the number of frames on the stack.
- Entry point: the outermost frame. In a Rust binary this is rarely your
main. The runtime starts a few functions first, such asstd::rt::lang_start, then calls yourmain. You will see these frames at the base of every flamegraph.
Seeing a real stack from Rust
The standard library can capture the current stack as a Backtrace. This is a good way to see the data a profiler works with.
use std::backtrace::Backtrace;
#[inline(never)]
fn leaf() {
let trace = Backtrace::force_capture();
println!("{trace}");
}
#[inline(never)]
fn middle() {
leaf();
}
fn main() {
middle();
}Run it with cargo run. The output lists numbered frames. Frame 0 is the innermost, so you will see leaf, then middle, then main, then several runtime functions. Lines starting with at show the source file and line number when debug information is available. A default cargo run uses the dev profile, which includes debug information. The two #[inline(never)] attributes stop the compiler from merging these tiny functions into their callers, which would hide frames. Inlining is covered in a later chapter.
Backtrace::force_capture captures the stack regardless of the RUST_BACKTRACE environment variable. Plain Backtrace::capture returns an empty, disabled trace unless that variable is set.
Where the names come from
The stack in memory contains return addresses, which are plain numbers. Nothing in memory says "this address belongs to is_prime". A tool must translate each address into a function name, and optionally a file and line. This translation is called symbolication. It needs two things:
- A symbol table, which maps address ranges to function names. Rust binaries keep one by default unless you strip them.
- Debug information, which maps addresses to source files and lines. The
debugsetting in Cargo controls whether the compiler emits it.
Rust function names in a binary are mangled, meaning the compiler encodes the crate, module path, and a hash into the symbol. A name like _ZN5myapp8is_prime17h3f2a9c1d5e7b4a60E is a mangled name. Tools demangle it to myapp::is_prime. If you see raw addresses such as 0x55d4c3a1b2f0 in profiler output instead of names, symbolication failed, usually because symbols were stripped or the tool could not find the binary.
The following table summarizes what each piece of data gives you.
| Data | What it provides | Typical failure when missing |
|---|---|---|
| Return addresses on the stack | The shape of the call chain | Truncated or broken stacks |
| Symbol table | Function names | Output shows raw hex addresses |
| Debug information | Source file and line numbers, and inlined frames | Names appear, but no lines and fewer frames |
Why a profile is a pile of stacks
A single stack answers one question: what was the program doing at this instant? One answer is not useful on its own, because the instant might be unrepresentative. But many stacks, collected at different moments, give a statistical picture. If 900 of 1,000 stacks contain is_prime as the leaf, the program spent roughly 90% of its CPU time inside that function.
This is the central idea of the whole tutorial. A profile is not a timeline of every call. It is a count of how often each distinct stack appeared. The chapter on sampling profilers describes how the stacks are collected. The chapter on flamegraph anatomy shows how the counts are drawn.
To make the counting concrete, suppose a profiler collected these stacks, written in the entry-first format, with a count after each:
main;count_primes;is_prime 900
main;count_primes 60
main 40The three lines hold 1,000 samples in total. Notice that main appears in all of them, but it is the leaf of only 40. This difference matters:
- Self time (or exclusive time) for a function is the number of samples where it is the leaf. Here
is_primehas 900,count_primeshas 60, andmainhas 40. - Total time (or inclusive time) is the number of samples where it appears anywhere in the stack. Here
mainhas 1,000,count_primeshas 960, andis_primehas 900.
Flamegraphs draw total time as width, and the part of a box not covered by its callees is self time. You will use both measures to find hotspots.
Edge cases that affect stacks
Real stacks are messier than the example above. These are the issues you will run into.
Recursion
A recursive function appears many times in one stack, for example fib;fib;fib;fib. When counting total time, a good tool counts each sample once per function, not once per frame. Otherwise a function would be credited with more than 100% of the time. Flamegraphs avoid this by drawing each recursive level as its own box stacked higher.
Inlining
The compiler can copy a small function's body into its caller. After that, the callee has no frame of its own at run time, and a stack read from raw return addresses lacks it. Debug information lets tools reconstruct these "virtual" frames. Without it, an inlined function's time is attributed to its caller. Release builds inline aggressively, so this affects the profiles you care about most.
Tail calls and missing frames
Some optimizations replace a call with a jump, so the caller's frame is gone before the callee runs. The callee's return goes straight to the caller's caller. Such a function does not show up in the stack. This is normal and not an error in the tool.
Walking the stack can fail
To record a stack, a profiler must find each frame's return address by following a chain. Two main techniques exist: following saved frame pointers, or interpreting DWARF unwind tables. Optimized Rust code often does not keep frame pointers, and a walker that expects them will cut stacks short. The chapter on stack unwinding explains the trade-offs and how to configure each.
Threads
Each thread has its own stack. A program with eight worker threads has eight separate stacks at any moment. A profiler samples them individually, and the results are merged into one graph. The chapter on threaded and async programs returns to this.
Common mistakes
- Treating the stack as a log. A stack shows the current chain of calls, not past ones. A function that already returned does not appear.
- Reading order backward. Confirm whether your tool prints the leaf first or last.
- Blaming the entry frames.
mainand the runtime frames sit in almost every stack, so they always have a large total time. That says nothing about where the cost is. Look at self time. - Expecting names without symbols. If output shows addresses, fix the build settings before drawing any conclusions. The next chapters show how.
Exercise
A profiler collected 500 samples. Their stacks, written entry-first, were: main;load;parse 300 times, main;load 50 times, and main;render 150 times. What are the self time and the total time, in samples, of load? Which function has the highest self time?
Show answer
load has a self time of 50 samples, because it is the leaf only in main;load. Its total time is 350 samples, because it appears in both main;load;parse (300) and main;load (50). The function with the highest self time is parse with 300 samples, even though load and main have larger total times.