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 read one for hotspots. It covers what changes when a program runs several threads or uses an async runtime.
One graph, many threads
perf samples every thread in the process. The flamegraph tools then merge all those samples into one picture. Each box's width is the share of all samples, not the share of one thread's time.
This has two consequences:
- Eight busy threads fill the graph eight times faster than one busy thread. A function that looks wide may be spread across many cores.
- Idle threads produce samples too, usually in frames such as
futex_waitorepoll_wait. These can make up a large part of the graph without costing any useful CPU.
The perf script output starts each stack with the thread's name. The folded stacks therefore get a separate root box for each distinct thread name. Naming your threads lets you read the graph per role.
use std::thread;
fn busy(n: u64) -> u64 {
(0..n).fold(0u64, |acc, x| acc.wrapping_add(x.wrapping_mul(x) ^ acc))
}
fn main() {
let mut handles = Vec::new();
for (name, work) in [("hasher", 400_000_000u64), ("summer", 100_000_000u64)] {
let handle = thread::Builder::new()
.name(name.to_string())
.spawn(move || busy(work))
.unwrap();
handles.push(handle);
}
for h in handles {
println!("{}", h.join().unwrap());
}
}Profile it with cargo flamegraph --bin myapp. You should see two root boxes, hasher and summer, and hasher should be about four times wider. Linux limits thread names to 15 characters, so longer names are cut off.
Separating threads when names are not enough
Thread pools often give every worker the same name, so their samples merge into one root. That is usually what you want. To keep workers apart, ask the collapse step to add the thread ID:
perf script | inferno-collapse-perf --tid | inferno-flamegraph > threads.svgIf the worker boxes have very different widths, the load is unbalanced. That points to a scheduling or work-splitting problem, not a slow function.
Async code
An async runtime such as Tokio runs many tasks on a few worker threads. A sampler sees only what is on a thread's stack at that instant. For async code this means:
- Stacks start at the runtime's worker loop, for example
tokio-runtime-w(the name is truncated), then show the scheduler, then thepollof your future. - Your async functions appear as
{async_fn#0}or{{closure}}frames. The state machine is polled from the top each time, so you see where the CPU is working now, not the chain of.awaitcalls that led to the task. - Time spent waiting on I/O or a timer is not on any stack, so it does not appear.
Name the runtime's threads so they are easy to find:
use tokio::runtime::Builder;
fn main() {
let rt = Builder::new_multi_thread()
.worker_threads(4)
.thread_name("async-worker")
.build()
.unwrap();
rt.block_on(async {
let tasks: Vec<_> = (0..8)
.map(|i| tokio::spawn(async move { (0..50_000_000u64).fold(i, |a, x| a ^ x) }))
.collect();
for t in tasks {
println!("{}", t.await.unwrap());
}
});
}This needs tokio = { version = "1", features = ["rt-multi-thread", "macros"] } in Cargo.toml. Heavy loops like this one block a worker. In real code you would move them to spawn_blocking, and the flamegraph will then show them under a separate blocking-pool thread name.
Exercise
A flamegraph of an async service has a very wide box under async-worker ending in epoll_wait, and your own functions are narrow. Is epoll_wait the hotspot to optimize?
Show answer
No. epoll_wait is where idle worker threads wait for I/O events, so those samples show idle time, not work. Look at the frames that run your own code. If they are narrow too, the program is probably waiting on I/O or other tasks, which a CPU flamegraph cannot show.