Sub topic 5
Choosing a workload worth profiling
A flamegraph describes the run you profiled and nothing else. If the run does not look like real use, the graph points at the wrong functions. This chapter covers how to pick, build and check a workload before you generate any graphs.
This chapter assumes you can build a Rust release binary, run commands in a terminal, and that you know how sampling works: the profiler records the call stack at a fixed rate, and functions that appear in more samples used more CPU time.
Why the workload decides the answer
A sampling profiler counts where the program was when it was interrupted. It has no opinion about which code matters. If your test input exercises a path that real users rarely hit, that path will dominate the graph and the real hot path will be a thin sliver or missing entirely.
Three properties of a workload affect the result:
- Representativeness. The inputs and code paths match what the program does in production or in the use case you care about.
- Duration. The run is long enough to collect many samples.
- Stability. Repeated runs give similar graphs, so you can tell a real change from noise.
Start from the question
Before you pick a workload, write down what you want to be faster. Examples:
- "Parsing a 50 MB log file takes too long."
- "Request latency rises under 200 concurrent clients."
- "Startup takes two seconds."
Each question implies a different workload. Startup needs a run that exits right after initialization, and a throughput question needs a long, steady load. Profiling the whole program when you only care about one phase mixes unrelated costs into one graph.
Sizing the run: how many samples you need
At a sampling rate of 99 Hz, the profiler collects about 99 samples per second of CPU time. A 2-second run gives roughly 200 samples. That is too few to trust small frames. A frame with 4 samples out of 200 is 2% of the graph, but one sample more or less changes it by 25%.
A practical rule is to aim for at least a few thousand samples. At 99 Hz that means 30 seconds or more of CPU time. At 997 Hz you reach the same count in about 3 seconds, but the profiler itself adds more overhead.
| Goal | Typical run time at 99 Hz | Samples |
|---|---|---|
| Spot a dominant hotspot (over 30% of time) | 2 to 5 seconds | 200 to 500 |
| Rank mid-sized costs (5% to 30%) | 20 to 30 seconds | 2,000 to 3,000 |
| Find small costs (1% to 5%) | 60 seconds or more | 6,000 or more |
You can also repeat a short workload inside the program, or in a loop in a benchmark, to collect more samples without changing what each iteration does.
Prefer realistic inputs
Synthetic data is convenient but often misleading. Some common traps:
- Tiny inputs. Small data fits in CPU caches. A function that looks cheap on 1,000 items can be slow on 10 million because it misses the cache.
- Uniform data. Random or repeated values can hide branch misprediction, hash collisions, or worst-case sorting behavior.
- Empty or cold state. A cache, connection pool or database that is empty changes what the program does. Decide whether you want to profile the warm or the cold case.
- Missing I/O. Replacing a file or network call with an in-memory stub removes real costs, and the CPU graph will overstate the share of your own code.
When you can, use a copy of real data, a recorded request log replayed against the program, or a generator that matches the size and shape of real input.
Keep the workload deterministic
Variation between runs makes before-and-after comparisons hard. Reduce it:
- Seed random number generators with a fixed value.
- Read inputs from files instead of generating them differently each time.
- Avoid wall-clock dependent behavior such as timeouts and retries during profiling.
- Close other heavy programs on the machine. Background load adds noise to timing, although a CPU profile only counts samples for your process.
Exclude setup and teardown
If the program spends 3 seconds loading data and 1 second doing the work you care about, the graph shows loading as the biggest tower. There are three ways to deal with this:
- Accept it and read only the part of the graph under the function that does the work.
- Make the work phase longer, for example by processing the data many times.
- Move the interesting code into a benchmark or a small binary that does less setup.
The third option is often best. A dedicated profiling binary or a Criterion benchmark gives you control over what runs.
A worked example: making a workload from the sample program
The sample program from this tutorial counts primes below 100,000 by trial division. Here is a version with the limit read from the command line, so you can choose the run size without recompiling.
use std::env;
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() {
let limit: u64 = env::args()
.nth(1)
.and_then(|s| s.parse().ok())
.unwrap_or(100_000);
println!("{}", count_primes(limit));
}Time a few sizes before you profile. Use the release build:
cargo build --release
time ./target/release/myapp 20000
time ./target/release/myapp 100000
time ./target/release/myapp 200000Trial division over 2..n is quadratic in the limit, so doubling the limit should roughly quadruple the time. If the timings follow that pattern, the workload scales predictably. Pick the size that runs for several seconds, then profile it:
cargo flamegraph --bin myapp -- 200000Everything after -- goes to your program, not to cargo-flamegraph.
Profiling a benchmark or a test
When the real program is hard to drive, profile a benchmark target. This gives you a repeatable workload with its own setup code. The --bench flag is passed through so the harness runs in benchmark mode:
cargo flamegraph --bench my_bench -- --benchThe benchmark harness may add its own frames, such as warm-up and statistics code. Look for your functions under the harness and ignore the rest. Criterion also runs each benchmark many times, which helps with the sample count.
Profiling a unit test works too, but tests are rarely representative. They use small inputs, assert on results, and often build fixtures. Use tests for a quick look and a benchmark for a decision.
Check that the workload is good
Run through this list before you trust a graph:
- Run it twice. The shapes of the two graphs should match, and the widths of the main frames should differ by only a few percent.
- Check the total sample count. The profiler reports it, and
perf reportshows it too. If it is under a few hundred, run longer. - Compare with production behavior. If you have production metrics or traces, check that the functions you expect to be busy appear in the graph.
- Look for harness frames at the top. If most of the width is in input generation, logging or setup, the workload is not testing your code.
- Vary the input size. If the hotspot changes as input grows, you have found a scaling issue, and you should profile at the size you care about.
Several workloads, not one
A program often has more than one important behavior. A web service might handle many small requests and a few large uploads. A single workload will favor one. Profile each important scenario separately and keep the graphs side by side. If a function is hot in all of them, fixing it pays off broadly. If it is hot in only one, the payoff depends on how often that scenario occurs.
Common mistakes
- Profiling for one second and drawing conclusions from 1% frames.
- Using a workload that finishes before the program reaches steady state, such as before caches fill or a thread pool starts.
- Changing the input between the before and after runs, then crediting a code change for the difference.
- Optimizing a function because it is wide in a graph built from an unrealistic input.
- Forgetting that a CPU flamegraph omits time spent waiting. A program that is slow because it waits on disk or the network can show a tiny, uninformative graph.
Exercise
You profile a program for 3 seconds at 99 Hz and see a frame covering 2% of the graph. A colleague wants to optimize it. What do you check first, and what would you change about the workload?
Show answer
Three seconds at 99 Hz gives about 300 samples, so a 2% frame is only about 6 samples and the estimate is unreliable. Run the workload longer, or repeat it in a loop, to collect a few thousand samples. Also confirm the input is realistic and fixed, repeat the run to see whether the frame stays near 2%, and only then decide whether it is worth optimizing.
Exercise
Your program loads a 2 GB file, which takes 8 seconds, then processes it in 1 second. The flamegraph is dominated by the loader. Name two ways to get a graph that shows the processing cost.
Show answer
Repeat the processing step many times after loading once, so it collects more samples than the loader. Alternatively, write a benchmark or small profiling binary that builds the data in memory and runs only the processing function. Reading just the subtree under the processing function in the existing graph is a third option, but it has few samples.