Sub topic 2
How sampling profilers work
This chapter explains how a sampling profiler turns a running program into data. It also covers how accurate that data is and what can bias it. It assumes you can build and run a Rust program with Cargo and that you know what a call stack is (a list of the functions currently executing, from main down to the innermost call). We build the flamegraph itself in the next chapter.
The core idea: look at the program, repeatedly
A profiler answers one question: where does the time go? There are two broad ways to find out.
- Instrumentation adds code to every function (or lets the compiler add it) to record when the function starts and ends. The result is exact. The cost is that the added code changes the timing, and small, hot functions are distorted the most.
- Sampling leaves your code alone. At regular intervals, the profiler interrupts the program, records the current call stack, and lets the program continue. After thousands of interruptions, the functions that appear in many samples are the ones where time is spent.
Flamegraph tooling for Rust (perf, cargo flamegraph, inferno) is built on sampling. A sample is a photograph of the program at one instant. A profile is a large pile of such photographs, counted.
What happens during one sample
On Linux, perf asks the kernel to generate an event at a fixed rate. Each event runs this sequence:
- A timer or a CPU performance counter fires. The CPU interrupts whatever code is running on that core.
- The kernel reads the instruction pointer (the address of the instruction being executed) and the process ID and thread ID.
- The kernel walks the stack from that point upward, collecting one return address per frame. This is the stack trace. How the walk finds frames is the topic of a later chapter on frame pointers and DWARF.
- The kernel writes the record to a buffer and resumes the program.
- Later, tools translate addresses into function names and source lines using the symbols in your binary.
The program is stopped for only a few microseconds per sample. At low frequencies that is a tiny share of the run, so the program behaves almost as it normally does. This low overhead is why sampling is the usual first choice for release builds.
Sampling frequency
The sampling frequency is how many samples are taken per second of CPU time, in hertz (Hz). It controls a trade-off.
| Frequency | Samples in 10 s | Effect |
|---|---|---|
| 99 Hz | about 990 | Very low overhead. Fine for programs that run for several seconds. |
| 997 Hz | about 9,970 | More detail for short runs. `cargo flamegraph` uses this by default. |
| 4000 Hz | about 40,000 | `perf record` default. More overhead and much larger data files. |
Two details are worth knowing.
First, people often choose 99 Hz instead of 100 Hz on purpose. Many things in a system happen on round-number schedules, such as timer ticks and periodic tasks. If you sample at exactly 100 Hz, you can fall into lockstep with such a task and see it in every sample or in none. A slightly odd rate drifts relative to those schedules. For the same reason 997 is prime.
Second, a higher frequency does not make a short program's profile more truthful in every respect. It gives you more samples, which reduces random error, but it also increases the perturbation of the program. Choose the lowest frequency that gives you enough samples.
How many samples are enough?
A sampling profile is an estimate, and estimates have error. Suppose a function really accounts for a share p of CPU time, and you take n samples. The measured share varies from run to run with a standard error of about sqrt(p * (1 - p) / n). For a rough 95% interval, double it.
For a function that truly uses 20% of the time:
- With 100 samples (about one second at 99 Hz), the standard error is about 4 percentage points. The 95% range is roughly 12% to 28%.
- With 990 samples (ten seconds at 99 Hz), the standard error is about 1.3 points. The range is roughly 17.5% to 22.5%.
The practical rules that follow:
- Large hotspots (tens of percent) show up reliably even in short runs.
- Small differences (a function at 3% versus 4%) are inside the noise unless you collect many thousands of samples.
- The error shrinks with the square root of
n. Four times the samples halves the error, so running a program 100 times longer is rarely the best way to get precision.
Seeing the sample counts yourself
The following program is the one we will profile throughout this tutorial. It is slow on purpose. Almost all of its time is spent in the trial-division loop inside is_prime.
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));
}Build it in release mode with debug info (the next chapter explains why), then record at 99 Hz with call graphs:
RUSTFLAGS="-C force-frame-pointers=yes" cargo build --release
perf record -F 99 -g -- ./target/release/myapp
perf report --stdio --no-children | head -n 30If you configured debug = true under [profile.release] in Cargo.toml, the report names the functions. You should see is_prime (or the closure inside it) with a share close to 100% of the samples, because everything else in the program is nearly free.
Under the hood, a profile is only a table of stacks and counts. This small program shows the aggregation step on its own. It takes a list of sampled stacks, written outermost frame first, and prints them in the "folded" format used by flamegraph tools: frames joined by semicolons, then a space and a count.
use std::collections::BTreeMap;
fn main() {
let samples: Vec<Vec<&str>> = vec![
vec!["main", "count_primes", "is_prime"],
vec!["main", "count_primes", "is_prime"],
vec!["main", "count_primes", "is_prime"],
vec!["main", "count_primes"],
vec!["main"],
];
let mut counts: BTreeMap<String, usize> = BTreeMap::new();
for stack in &samples {
*counts.entry(stack.join(";")).or_insert(0) += 1;
}
let total = samples.len();
for (stack, n) in &counts {
println!("{stack} {n}");
}
println!("total samples: {total}");
}The output is:
main 1
main;count_primes 1
main;count_primes;is_prime 3
total samples: 5Here is_prime was on the stack in 3 of 5 samples, so it gets 60% of the estimated time. Counting identical stacks is the whole trick. A real profile does the same with thousands of samples.
What a sample counts: self time and total time
Each sample records the whole stack, but the innermost frame is the function that was actually executing. That gives two measurements for each function:
- Self time is the number of samples where the function is the innermost frame. It measures time spent in the function's own instructions.
- Total time is the number of samples where the function appears anywhere on the stack. It includes time in everything the function calls.
In the folded example above, count_primes has a self count of 1 and a total count of 4. main has a self count of 1 and a total count of 5. A function with a large total but a tiny self count is just a caller. The work is further down. You will use this distinction constantly when reading flamegraphs.
What the samples measure, and what they do not
Sampling gives a statistical picture with specific blind spots.
It measures CPU time, not elapsed time. The usual events (cpu-clock or cycle counters) tick only while a thread runs on a CPU. A thread that is waiting for a lock, a disk read, a network reply or sleep is not on a CPU and gets no samples. A program that spends 90% of its wall-clock time waiting can still show a profile full of its other 10%. The final chapter of this tutorial covers off-CPU profiling.
It sees the stack only at sample points. Anything shorter than the sample interval can still be caught, but only with probability proportional to its duration. A function that runs for 1 ms once a second has a 10% chance of being hit per second at 100 Hz. Over a long run it is represented fairly, which is why the sample count matters.
It has skid. When a performance counter overflows, the interrupt is delivered a few instructions after the instruction that caused it. The recorded instruction pointer can be slightly off. This rarely matters at function level. It matters if you read line-level or instruction-level attribution.
It can be biased by what it perturbs. Sampling at very high frequencies makes the program slower, and frequent interrupts can disturb caches and branch predictors. The profile then shows a program slightly different from the one you normally run.
It can fail to see the whole stack. If the kernel cannot walk the stack, because frames were not preserved or symbols are missing, samples end up truncated or labeled with raw addresses. The result looks like a plausible profile but attributes time to the wrong callers. Tooling hides this less than you might expect, so check that your stacks reach main before you trust any numbers.
Choosing a frequency in practice
- Start with the tool's default.
cargo flamegraphworks well for most programs. - If the run lasts under a second, raise the frequency (for example
-F 997or higher) or loop the workload so the run is longer. Aim for at least a few thousand samples when you need to compare functions that are close in size. - If you suspect lockstep with periodic work, change the frequency to a different odd or prime value and check that the profile stays the same.
- Repeat the run once. If the top functions and their approximate shares are stable, you have enough samples. If they move around, you need more.
Exercise
A function accounts for about 10% of your program's CPU time. You record 400 samples. Using the standard error formula sqrt(p(1-p)/n), roughly what range of measured shares should you expect from run to run (a 95% interval), and what should you do if you need to tell 10% from 9%?
Show answer
The standard error is sqrt(0.1 * 0.9 / 400) = sqrt(0.000225) = 0.015, or 1.5 percentage points. The 95% range is about twice that, so roughly 7% to 13%. A difference of one point is well inside this range, so 400 samples cannot separate 10% from 9%. To cut the error to about 0.5 points you need about nine times as many samples, around 3,600. You get them by running longer, repeating the workload in a loop, or raising the sampling frequency. For a change that small, a benchmark is a better tool than a profile.
Exercise
A Rust service spends most of its wall-clock time waiting on a database. Its CPU flamegraph shows that JSON parsing is the largest block. Does this mean JSON parsing is the main reason requests are slow?
Show answer
Not necessarily. CPU sampling only records time while threads are running on a CPU. Time spent waiting on the database produces no samples, so the flamegraph shows how the CPU time is divided, not how the request latency is divided. JSON parsing may be the largest share of the CPU work and still be a small share of the total request time. To see the waiting, you need an off-CPU profile or tracing that measures wall-clock time.