Sub topic 2
Measure first: counting allocations and profiling
This chapter assumes you know ownership and borrowing, the basics of Vec and String, and how to run cargo test and cargo bench. Later chapters remove allocations. Here you learn to count them, so you can tell whether a change helped.
Why measure before changing code
An allocation is a request to the global allocator for heap memory. It costs time, and it can fragment memory. In most programs, though, only a few call sites allocate often enough to matter. Rewriting code that runs once at startup gains nothing. Rewriting a loop that runs a million times can gain a lot.
You need two numbers for any suspect code: how many allocations happen, and whether those allocations are a large share of the run time. A counter answers the first question. A profiler answers the second.
Count allocations with a global allocator wrapper
Rust lets you replace the program's allocator with #[global_allocator]. A thin wrapper around the system allocator can increment a counter on every alloc call.
use std::alloc::{GlobalAlloc, Layout, System};
use std::sync::atomic::{AtomicUsize, Ordering};
struct Counting;
static ALLOCS: AtomicUsize = AtomicUsize::new(0);
unsafe impl GlobalAlloc for Counting {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
ALLOCS.fetch_add(1, Ordering::Relaxed);
unsafe { System.alloc(layout) }
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
unsafe { System.dealloc(ptr, layout) }
}
}
#[global_allocator]
static GLOBAL: Counting = Counting;
fn main() {
let before = ALLOCS.load(Ordering::Relaxed);
let v: Vec<u32> = (0..1000).collect();
let after = ALLOCS.load(Ordering::Relaxed);
println!("len = {}, allocations = {}", v.len(), after - before);
}The program prints len = 1000, allocations = 1. The range reports its exact length, so collect reserves the space once.
The counter changes only alloc. The default realloc calls alloc and dealloc internally, so growth of a Vec is counted too. If you also override realloc, count it there.
Wrap the measurement in a helper
Reading the counter twice by hand gets repetitive. A small function makes before-and-after comparisons easy. Add it to the program above.
fn allocations_in<R>(f: impl FnOnce() -> R) -> (R, usize) {
let before = ALLOCS.load(Ordering::Relaxed);
let result = f();
let after = ALLOCS.load(Ordering::Relaxed);
(result, after - before)
}Call it as let (v, n) = allocations_in(|| build_the_thing());. Compare n for the old and new versions of a function, with the same input each time.
Limits of a counter
- The counter is process-wide. Other threads add to it.
cargo testruns tests on several threads by default, so usecargo test -- --test-threads=1or measure in a plain binary. - It counts calls, not bytes. One allocation of 1 GB and one of 8 bytes both add one.
- It does not say where an allocation came from, or how much time it cost.
- Use a release build (
cargo run --release). Debug builds skip optimizations that remove allocations, so the counts can differ.
Find the source with a profiler
When you do not yet know which code allocates, use a tool that records call stacks.
| Tool | What it shows | Notes |
|---|---|---|
| `dhat` crate | Allocation counts, bytes and peak size per call site | Runs inside your program, works on all platforms |
| heaptrack | Allocation hot spots and a timeline of memory use | Linux, no code changes |
| `perf` or a flame graph | Where CPU time goes, including time in `malloc` and `free` | Shows whether allocation is significant at all |
Build with debug symbols in release mode (debug = true under [profile.release] in Cargo.toml). Otherwise call stacks are hard to read.
A measurement workflow
Make one change at a time. A lower count with no gain in time is usually not worth the added complexity.
Exercise
You wrap a function in your counting helper inside a #[test] and get a different count on each run. What is the most likely cause, and how do you fix it?
Show answer
Tests run in parallel threads, and the counter is process-wide, so other tests' allocations are included. Run with cargo test -- --test-threads=1, or measure in a standalone binary built with --release.