Sub topic 14
What CPU flamegraphs cannot show: off-CPU time
This chapter assumes you can build a Rust release binary with debug symbols, run cargo flamegraph, and read a basic flamegraph. It explains what a CPU flamegraph leaves out and what to do about it.
What a CPU flamegraph measures
A sampling profiler like perf interrupts the CPU at a fixed rate, such as 99 times per second. Each interrupt records the call stack of the code running at that moment. A thread that is not running on a CPU core is never interrupted, so it never appears in the samples.
This means a CPU flamegraph shows on-CPU time: time spent executing instructions. It does not show off-CPU time: time a thread spends waiting. Common causes of waiting are:
- Blocking on a lock (
Mutex::lock) held by another thread. - Reading from a disk, socket, or pipe.
thread::sleepor waiting on a channel.- Being descheduled by the operating system because other threads need the core.
A program can take ten seconds of wall-clock time and show only one second of samples. The flamegraph then describes that one second and says nothing about the other nine.
A program that waits
This program spends most of its time sleeping, and a small part computing.
use std::thread::sleep;
use std::time::{Duration, Instant};
fn compute() -> u64 {
(0..50_000_000u64).fold(0, |acc, n| acc.wrapping_add(n * n))
}
fn wait_for_io() {
sleep(Duration::from_millis(900));
}
fn main() {
let start = Instant::now();
wait_for_io();
let result = compute();
println!("result {} in {:?}", result, start.elapsed());
}A flamegraph of this program is dominated by compute. The 900 ms sleep is invisible, even though it is likely the largest share of the run time. If you tuned only what the graph shows, you would speed up the smaller part of the problem.
Signs that you have an off-CPU problem
Compare wall-clock time with CPU time before you trust a flamegraph. The time command reports both.
time ./target/release/myappRead the three lines it prints:
| Field | Meaning |
|---|---|
| real | Wall-clock time from start to finish |
| user | CPU time spent in your code |
| sys | CPU time spent in the kernel on your behalf |
If real is much larger than user + sys, the process spent a lot of time waiting. A CPU flamegraph cannot explain that gap. If user + sys is larger than real, the program is using several threads at once, which is normal for parallel code.
Low CPU usage in top while the program feels slow points the same way.
Ways to look at off-CPU time
Several approaches exist, and each has a cost.
- Trace scheduler events. On Linux,
perfcan record when a thread leaves and returns to the CPU, usingperf record -e sched:sched_switch -g. Folding those stacks with inferno produces an off-CPU flamegraph where width means time spent blocked. This needs elevated privileges and produces large data files. - Use eBPF tools. Tools such as
offcputimefrom the BCC collection aggregate blocked time in the kernel, which keeps overhead lower than recording every event. - Add timing to your own code. Wrap suspect calls with
Instant::now()and log the elapsed time. This is crude but works on any platform. - Use async-aware tools. For async programs,
tokio-consoleshows how long tasks wait and how often they are polled. A task waiting on a future is not a blocked thread, so thread-level tools can mislead.
Off-CPU flamegraphs include idle threads too, such as a worker waiting for jobs. Wide idle stacks are usually normal. Look for blocking inside the path of the work you care about.
Choosing the right tool
| Symptom | Likely cause | Start with |
|---|---|---|
| High CPU use, slow | Hot code | CPU flamegraph |
| Low CPU use, slow | Waiting on I/O or locks | Off-CPU trace or timing |
| One core busy, others idle | Serial bottleneck or lock | Per-thread view, off-CPU trace |
| Slow async service | Tasks waiting or blocked executor | `tokio-console` |
Exercise
A program takes 12 seconds by time, with user 1.1 s and sys 0.2 s. Its CPU flamegraph shows parse_config as the widest frame. Should you optimize parse_config first? Explain.
Show answer
Probably not. Only about 1.3 s of the 12 s was spent on CPU, so the flamegraph covers roughly 11% of the run time. The remaining time was spent waiting, for example on I/O or locks. Investigate off-CPU time with a scheduler trace, an eBPF tool, or manual timing before optimizing parse_config.
Exercise
In the sleeping example above, why does wait_for_io not show up in the flamegraph?
Show answer
thread::sleep takes the thread off the CPU, so the profiler's timer interrupts find no running code from that thread and record no samples for it.