Sub topic 14
What CPU flamegraphs cannot show: off-CPU time
This chapter assumes you can build and run Rust programs in release mode, you have produced a flamegraph with cargo flamegraph or perf and inferno, and you know that a flamegraph is built from sampled call stacks. Here you will learn what a CPU flamegraph leaves out, how to tell that your program is affected, and what to use instead.
On-CPU and off-CPU time
A thread is always in one of two broad states.
- On-CPU: the thread is running instructions on a core.
- Off-CPU: the thread exists but is not running. It may be sleeping, blocked on a read, waiting for a lock, parked while waiting for work, or runnable but waiting for the scheduler to give it a core.
The profilers in the earlier chapters sample on a timer tied to CPU activity. On Linux, perf record usually samples on the cycles event, or on cpu-clock when hardware counters are unavailable. In both cases a thread that is not running produces no samples. A CPU flamegraph therefore describes only the time your program spent executing.
That is the right view when the program is compute-bound. It is a misleading view when the program is slow because it waits. Wall-clock time is what the user experiences. A request that takes 100 ms and spends 90 ms blocked looks, in a CPU flamegraph, like a program that spends all its time in the remaining 10 ms.
A program the flamegraph misreads
The program below handles 50 simulated requests. Each request does 10 ms of computation, then waits 90 ms. The wait stands in for a database call, a network round trip, or a lock held by another thread.
use std::hint::black_box;
use std::thread;
use std::time::{Duration, Instant};
fn busy_work(ms: u64) -> u64 {
let start = Instant::now();
let mut x: u64 = 0;
while start.elapsed() < Duration::from_millis(ms) {
x = x.wrapping_add(1);
black_box(x);
}
x
}
fn wait_for_backend(ms: u64) {
thread::sleep(Duration::from_millis(ms));
}
fn handle_request() {
busy_work(10);
wait_for_backend(90);
}
fn main() {
let start = Instant::now();
for _ in 0..50 {
handle_request();
}
println!("wall time: {:?}", start.elapsed());
}Build it with debug symbols as described in the earlier chapter, then run it under time:
cargo build --release
time ./target/release/myappYou should see output of roughly this shape. The exact numbers will vary by machine.
wall time: 5.0s
real 0m5.003s
user 0m0.490s
sys 0m0.005sreal is wall-clock time. user and sys add up to the CPU time the process consumed. Here the process ran for about half a second out of five. If you run cargo flamegraph on this program, the graph will show busy_work filling almost the whole width, and wait_for_backend will be missing or tiny. Width is a share of samples, and nearly all samples came from the 10% of the time when the thread was running. The graph is accurate about CPU time, but it says nothing about the other 90%.
Detecting the problem before you profile
Compare CPU time with wall time first. This costs nothing and avoids hours of optimizing the wrong thing.
- If
user + sysis close torealfor a single-threaded program, the program is CPU-bound and a CPU flamegraph is the right tool. - If
user + sysis much smaller thanreal, the program spends most of its time off-CPU. - For multithreaded programs,
user + syscan exceedreal, because several cores run at once. Compare it withreal × number of busy threadsinstead. Low utilization of the cores you expected to be busy is the signal.
Other hints that point the same way:
- The flamegraph is sparse, with few samples, even though the run was long.
- Throughput does not improve when you add CPU-bound optimizations.
- Latency varies widely between runs while CPU time stays steady.
Measuring off-CPU time
Off-CPU profiling records a stack when a thread stops running and measures how long it stays stopped. The result is a flamegraph whose widths are time spent blocked, not CPU samples. These tools are Linux-specific and usually need root.
The BCC tool offcputime hooks the kernel scheduler and prints folded stacks. Its package name varies by distribution. On Debian and Ubuntu the command is offcputime-bpfcc.
# Find the process ID, then record 10 seconds of off-CPU stacks
pid=$(pgrep myapp)
sudo offcputime-bpfcc -f -p "$pid" 10 > off.folded
# Render with inferno. Values are microseconds blocked.
inferno-flamegraph --countname us < off.folded > off.svgThe -f flag writes the folded format that inferno-flamegraph reads, the same format inferno-collapse-perf produces. For the example program, the widest frame in off.svg should be the nanosleep system call under wait_for_backend, which is the 90 ms you could not see before.
You can also use perf alone, without BCC, by recording scheduler events:
sudo perf record -e sched:sched_switch -g -p "$pid" -- sleep 10
sudo perf scriptsched_switch fires each time the scheduler switches a thread out. Turning those events into per-stack blocked durations takes post-processing, and BCC does that for you. Use the perf route when you cannot install BCC.
Debug symbols matter here exactly as they did for CPU profiles. The Rust frames above the blocking system call need symbols and a reliable unwinding method, as covered in the earlier chapters on release builds and stack unwinding.
Reading an off-CPU graph
An off-CPU flamegraph has a trap of its own. Not all waiting is a problem.
- A worker thread parked while waiting for a job is idle by design. It will appear as a very wide frame, usually under a futex wait. Ignore it unless you expect that thread to be busy.
- A request thread blocked on a lock, a socket, or a disk read is time added to the request's latency. These are the frames to study.
- Time spent runnable but waiting for a core means the machine is oversubscribed. It points to a deployment or scheduling problem, not to a function to rewrite.
Always profile one process, ideally one thread role, and ask whose time the width represents. A wide frame in an off-CPU graph is only a problem if someone was waiting for that thread.
Contention that looks like CPU
Some waiting does burn CPU, and the CPU flamegraph then shows it as a hotspot. A spin lock, or a mutex that spins briefly before parking, shows up as on-CPU time in the lock's code. Seeing lock-related frames wide in a CPU graph is a sign of contention. The full cost, including the time threads spend parked after spinning, appears only in the off-CPU view. Use both graphs when you suspect locks.
Async Rust adds another gap
In async code, a task waiting on a future is not a thread blocked in the kernel. The runtime thread moves on to run other tasks, so the waiting task is neither on-CPU nor visible as off-CPU time of any thread. Neither kind of flamegraph shows how long a task spent waiting at an .await.
For async programs, add instrumentation that follows tasks rather than threads:
- The
tracingcrate with spans around request handlers gives per-request wall-clock durations, including await time. tokio-consoleshows each task's busy time and idle time, and flags tasks that block the executor.
A related mistake does show up in a CPU flamegraph. If you call a blocking function such as std::thread::sleep or a synchronous file read inside an async task, it stalls the whole runtime thread. The off-CPU graph shows that thread blocked in the system call, and that is the evidence you need to move the work to spawn_blocking or to an async API.
Choosing the right tool
| Symptom | Likely cause | First tool |
|---|---|---|
| `user + sys` close to `real`, flamegraph has wide frames | CPU-bound code | CPU flamegraph |
| `user + sys` far below `real`, one thread | Blocking I/O, sleep, or lock waits | Off-CPU flamegraph |
| Many threads, low core utilization | Lock contention or too little parallel work | Both graphs, then `perf` lock analysis |
| Async service with high latency and low CPU | Slow awaited dependency, or blocking call in a task | `tracing` spans, `tokio-console` |
| Good CPU profile but slow on a loaded machine | Waiting for a core | `perf sched` |
Limits to keep in mind
- Off-CPU tracing records every context switch, so overhead grows with how often threads block. Test on a short run before recording a busy production process.
- Off-CPU stacks of kernel waits can be deep and hard to read. Look first for the widest frame that sits directly below your own functions.
- On virtual machines and containers, hardware counters and BPF may be restricted. If
perf recordfalls back tocpu-clock, that is fine for CPU graphs but does not change anything about off-CPU limits. - Neither graph measures memory waits well. A thread stalled on cache misses is still on-CPU, and its time is attributed to the function that issued the loads.
Exercise
A Rust web service handles a request in 200 ms of wall time. Running under time for a load test shows real of 60 s and user + sys of 6 s for a single-threaded server. A CPU flamegraph shows 70% of samples in a JSON serialization function. A teammate wants to rewrite the serializer to make it faster. What should you check first, and why might the rewrite fail to help much?
Show answer
Check where the other 90% of the time goes, because CPU time is only 10% of wall time. The flamegraph covers only that 10%, so serialization is about 7% of total request time. Even making it free would cut latency by roughly 7%. Record an off-CPU flamegraph (for example with offcputime-bpfcc -f) or add tracing spans if the server is async, and find what the thread is blocked on, such as a database call, a lock, or a synchronous read. Optimize that first.