Sub topic 13
Profiling threaded and async programs
This chapter assumes you can already produce a flamegraph with cargo flamegraph or with perf and inferno, and that you can read a basic one: width is the share of samples, and the top edge is where the CPU was. It also assumes you know how to spawn threads with std::thread and have seen async fn and .await. The chapter covers what changes when more than one thread, or an executor, is involved.
What a flamegraph does with many threads
perf record samples every thread of the process. Each sample is a stack plus some metadata, including the thread it came from. If you do nothing, the folding step merges identical stacks regardless of thread. Two consequences follow.
- Width is CPU time summed over threads. If four threads each burn a full core for one second, the graph holds about four seconds of samples. A frame that is 50% wide used half of the total CPU time, not half of the elapsed time.
- Threads running the same code add up. Four workers all calling
count_primesproduce one widecount_primestower. This is usually what you want, but it hides imbalance between workers.
Samples only exist while a thread is running on a CPU. A thread blocked on a mutex, a channel, a socket or a sleep produces no samples. A program that is slow because its threads wait will therefore show a thin, unremarkable graph. The last section returns to this.
flowchart TDThe diagram below shows the path from threads to a single graph.
A multithreaded example
The program below runs three threads that count primes and one that computes a hash. It uses only the standard library. The threads are named, which matters in a moment.
use std::hint::black_box;
use std::thread;
fn is_prime(n: u64) -> bool {
if n < 2 {
return false;
}
(2..).take_while(|d| d * d <= n).all(|d| n % d != 0)
}
fn count_primes(start: u64, end: u64) -> usize {
(start..end).filter(|&n| is_prime(n)).count()
}
fn checksum(rounds: u64) -> u64 {
let mut h: u64 = 14695981039346656037;
for i in 0..rounds {
h ^= black_box(i);
h = h.wrapping_mul(1099511628211);
}
h
}
fn main() {
let mut handles = Vec::new();
for i in 0..3u64 {
let handle = thread::Builder::new()
.name(format!("prime-{i}"))
.spawn(move || count_primes(i * 2_000_000, (i + 1) * 2_000_000))
.unwrap();
handles.push(handle);
}
let hasher = thread::Builder::new()
.name("checksum".to_string())
.spawn(|| checksum(2_000_000_000))
.unwrap();
let total: usize = handles.into_iter().map(|h| h.join().unwrap()).sum();
println!("primes: {total}, checksum: {}", hasher.join().unwrap());
}Profile it as before, with debug symbols enabled in the release profile:
cargo flamegraph --bin myappOn Linux the kernel records each thread's name in a field called comm. perf script prints it at the start of every sample, and inferno-collapse-perf uses it as the bottom frame of the stack. With named threads you get separate towers called prime-0, prime-1, prime-2 and checksum, and the widths show how much CPU each one used. Without names, every thread gets the executable's name and the towers merge.
The kernel limits a thread name to 15 characters. Names such as database-writer-1 and database-writer-2 are cut to the same string and merge again, so keep the distinguishing part near the front.
Splitting and filtering by thread
With the manual pipeline you have more control. Use --tid to put the process and thread IDs in the root frame:
RUSTFLAGS="-C force-frame-pointers=yes" cargo build --release
perf record -F 99 -g -- ./target/release/myapp
perf script | inferno-collapse-perf --tid | inferno-flamegraph > per-thread.svgTo look at one thread only, filter before collapsing:
perf script --comms checksum | inferno-collapse-perf | inferno-flamegraph > checksum.svgA graph for one thread answers a narrower question: what is this thread doing with its time? The merged graph answers a broader one: where does the process spend CPU?
Thread pools and Rayon
In a pool, work moves between threads, so the root frames are the same for every worker. The useful structure appears higher up.
- Under Rayon, task code sits beneath frames such as
rayon_core::registry::WorkerThread::wait_until_cold,rayon_core::join::join_contextand the parallel iteratorbridgefunctions. These frames are scaffolding. Look for your own functions above them. - Idle workers that spin while looking for work to steal appear as wide scheduler frames with no application code. A large share of such frames suggests the work items are too small or too unevenly split. A very small share suggests the pool is busy.
- Recursion depth grows with the split depth. Deep, narrow towers of
join_contextare normal.
Async programs
An async function compiles to a state machine that implements Future. The executor calls poll on it. This changes what a stack means.
- A sample shows the code running now. The stack is the executor's worker loop, the task's
poll, then the chain of futures being polled. It is not the logical chain ofawaits that led there. - Suspended tasks have no stack. A task waiting on a timer or a socket is just data in memory. It cannot be sampled, so time spent waiting never appears.
- Spawned tasks lose their parent. A task created with
tokio::spawnstarts from the executor, not from the function that spawned it. You will not seemainor the request handler as its caller. - Names are less tidy. Async bodies show up as
myapp::handler::{{closure}}or aspollmethods on generated types. The function name is still readable, but there may be several{{closure}}frames in a row.
The main thing a CPU flamegraph reveals in async code is blocking: synchronous work running inside a task. That work holds an executor thread, delays every other task scheduled on it, and shows up as a wide frame directly under poll.
To try it, create a project with this dependency:
[dependencies]
tokio = { version = "1", features = ["rt-multi-thread", "macros", "time"] }
[profile.release]
debug = trueuse std::hint::black_box;
use std::time::Duration;
fn hash_work(seed: u64) -> u64 {
let mut h: u64 = 14695981039346656037 ^ seed;
for i in 0..400_000_000u64 {
h ^= black_box(i);
h = h.wrapping_mul(1099511628211);
}
h
}
async fn cpu_heavy_handler(id: u64) -> u64 {
// Synchronous work inside an async fn: it blocks the executor thread.
hash_work(id)
}
async fn waiting_handler(id: u64) -> u64 {
tokio::time::sleep(Duration::from_millis(500)).await;
id
}
#[tokio::main]
async fn main() {
let mut tasks = Vec::new();
for id in 0..8u64 {
tasks.push(tokio::spawn(cpu_heavy_handler(id)));
tasks.push(tokio::spawn(waiting_handler(id)));
}
let mut sum = 0u64;
for task in tasks {
sum = sum.wrapping_add(task.await.unwrap());
}
println!("{sum}");
}In the flamegraph, hash_work is wide, under cpu_heavy_handler, under tokio's task poll frames. waiting_handler is nearly invisible, even though each of those tasks takes half a second of wall time, because a sleeping task uses no CPU. The graph is correct. It answers where the CPU went, not where the time went.
The fix for blocking work is to move it off the executor, for example with tokio::task::spawn_blocking, or to run it on a Rayon pool. A second profile then shows the same hash_work width under different parent frames. The CPU cost is unchanged, but the executor threads are free for other tasks.
Common problems
| Symptom | Likely cause | What to do |
|---|---|---|
| One wide tower mixing several workers | Threads share a name or are unnamed | Name threads with `thread::Builder::name`, or use `--tid` |
| Graph looks tiny or flat though the program is slow | Threads are blocked, not running | Use an off-CPU approach, covered in the next chapter |
| Spawned task has no useful parent | Executor starts tasks from its own loop | Add `tracing` spans, or profile the task function directly |
| Broken or very short stacks in async code | Frame pointers missing in dependencies | Build with `-C force-frame-pointers=yes`, or record with `--call-graph dwarf` |
| Wide scheduler frames and little application code | Workers idle-spinning or work is too fine-grained | Increase task size or reduce the thread count |
Limits to keep in mind
A CPU flamegraph can only explain time spent running. For threaded and async code, that leaves some blind spots:
- Lock contention shows up only as time lost, not as a frame. A thread parked on a
Mutexis off the CPU. - Channel waits,
joincalls,.awaiton I/O andsleepall produce no samples while they wait. - Spinning is the exception. A spin lock or a brief spin phase before parking does burn CPU and does appear.
When wall-clock time is much larger than total CPU time, suspect waiting. Compare the two with time: if real is far higher than user + sys, a CPU flamegraph will not locate the problem.
Exercise
You profile an async web service with cargo flamegraph. Requests take 300 ms each, yet the flamegraph shows only a small parse_request frame and no database code. What does this suggest, and what would you do next?
Show answer
The service is probably spending most of its time waiting, likely on the database. Waiting tasks are suspended and use no CPU, so they produce no samples. The CPU profile is accurate but does not cover the problem. Confirm by comparing wall-clock time with CPU time, then use an off-CPU profile or tracing spans around the database calls to measure the wait.
Exercise
Your four worker threads are all spawned without names, and the flamegraph shows one tower for the whole program. Give two ways to see per-thread behavior.
Show answer
Name the threads with std::thread::Builder::name (keeping names unique within 15 characters) so each becomes its own root frame. Alternatively, run the manual pipeline with inferno-collapse-perf --tid to include thread IDs in the root frame, or filter with perf script --comms <name> and render one graph per thread.