Sub topic 2
Measure first: counting allocations and profiling
This chapter assumes you know ownership, borrowing and lifetimes, can use Vec, String and Box, are comfortable with iterators and closures, and can run cargo build, cargo test and cargo bench. It also assumes you know the stack and heap split from the previous chapter.
Removing allocations makes code harder to read. Do it only where it pays off, and check afterwards that it did. This chapter gives you two tools for that. One is a counting allocator you can drop into any binary or test. The other is a set of profilers that tell you which lines allocate and whether the allocations matter.
Why counting comes before optimizing
An allocation is a call into the global allocator. It costs time, because the allocator searches for free memory and may take locks or ask the operating system for more. It also scatters data around the heap, which hurts cache locality. But a single allocation is cheap, often tens of nanoseconds. A program that makes 100 allocations at startup has nothing to fix. A program that makes 100 allocations for every request, line or packet might.
Two questions decide whether to act:
- How many allocations happen per unit of work (per item, per request, per iteration)?
- Does the allocation cost show up in the metric you care about, such as latency, throughput or peak memory?
A counter answers the first question. A profiler or benchmark answers the second. You need both, because a count alone can mislead. Removing 1,000 allocations from a function that runs once saves nothing measurable.
A counting global allocator
Rust lets you replace the program's allocator with any type that implements GlobalAlloc. A thin wrapper around the system allocator that bumps a counter is enough to count allocations.
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 space once.
Here is how it works:
#[global_allocator]makes every heap request in the program, including those inside the standard library and your dependencies, go throughCounting.- Each method is
unsafebecause theGlobalAlloccontract is unsafe. The wrapper only forwards toSystem, so it keeps the same guarantees. Ordering::Relaxedis enough. You only need the counter to be atomic, not to order other memory operations.- The code reads the counter before and after the region of interest and subtracts. The
println!runs after the second read, so its own allocations are not counted.
Counting bytes and reallocations
Allocation count and allocated bytes tell different stories. Many small allocations and one huge one can have the same count. Track both, and handle realloc explicitly.
The default realloc implementation calls your alloc, copies the data, and calls your dealloc. That gets counted as one allocation. If you override realloc to forward to System.realloc, which can often grow a block in place, you must count it yourself or growth will vanish from your numbers.
use std::alloc::{GlobalAlloc, Layout, System};
use std::sync::atomic::{AtomicUsize, Ordering};
struct Counting;
static ALLOCS: AtomicUsize = AtomicUsize::new(0);
static BYTES: AtomicUsize = AtomicUsize::new(0);
unsafe impl GlobalAlloc for Counting {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
ALLOCS.fetch_add(1, Ordering::Relaxed);
BYTES.fetch_add(layout.size(), Ordering::Relaxed);
unsafe { System.alloc(layout) }
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
unsafe { System.dealloc(ptr, layout) }
}
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
ALLOCS.fetch_add(1, Ordering::Relaxed);
BYTES.fetch_add(new_size, Ordering::Relaxed);
unsafe { System.realloc(ptr, layout, new_size) }
}
}
#[global_allocator]
static GLOBAL: Counting = Counting;
/// Runs `f` and returns its result with the allocation count and bytes requested.
fn measure<T>(f: impl FnOnce() -> T) -> (T, usize, usize) {
let a0 = ALLOCS.load(Ordering::Relaxed);
let b0 = BYTES.load(Ordering::Relaxed);
let out = f();
let a1 = ALLOCS.load(Ordering::Relaxed);
let b1 = BYTES.load(Ordering::Relaxed);
(out, a1 - a0, b1 - b0)
}
fn grow_without_hint(n: u32) -> Vec<u32> {
let mut v = Vec::new();
for i in 0..n {
v.push(i);
}
v
}
fn grow_with_capacity(n: u32) -> Vec<u32> {
let mut v = Vec::with_capacity(n as usize);
for i in 0..n {
v.push(i);
}
v
}
fn main() {
let (_, a, b) = measure(|| grow_without_hint(1000));
println!("no hint: {a} allocations, {b} bytes requested");
let (_, a, b) = measure(|| grow_with_capacity(1000));
println!("with capacity: {a} allocations, {b} bytes requested");
}The first line reports roughly nine allocations. The vector starts with room for four u32 values and doubles each time it fills, and each growth step counts. The second line reports one allocation of 4,000 bytes. The exact growth numbers are an implementation detail of the standard library, so treat them as an illustration, not a guarantee.
BYTES counts bytes requested, not bytes live. To track peak memory, you would also subtract layout.size() in dealloc and record a high-water mark. That is easy to get subtly wrong under threads, which is one reason to use a profiler for memory-size questions.
Limits of the counter
- Global state. The counters are shared by all threads.
cargo testruns tests in parallel, so counts from two tests mix. Run allocation tests withcargo test -- --test-threads=1, or put them in their own integration test file with one test. - Background noise. Another thread, such as a logger or a runtime worker, can allocate during your measured region. Keep the measured region small and single-threaded.
- One allocator per binary. You can declare only one
#[global_allocator]. A counting allocator conflicts with a profiler that also installs its own allocator, so use them one at a time. - No call sites. The counter tells you how many allocations happened, not where. For that you need a profiler.
Profiling: finding where and how much
A profiler records which code paths allocate, how large and how long-lived the allocations are, and how that relates to total runtime. The common options for Rust are below.
| Tool | What it shows | Notes |
|---|---|---|
| `dhat` crate | Allocation sites, total and peak bytes, short-lived allocations | Pure Rust, works on any platform. Replaces the global allocator, so you can also assert on `dhat::HeapStats` in tests. |
| Valgrind DHAT (`valgrind --tool=dhat`) | Same kind of data without changing the code | Linux and macOS. Slows the program a lot. |
| `heaptrack` | Allocation sites over time, flame graphs of allocations | Linux. Attaches to an unmodified binary. |
| `cargo flamegraph` or `perf` | Where CPU time goes, including time inside `malloc` and `free` | Shows whether allocation is a large share of runtime. |
| `criterion` or `cargo bench` | Wall-clock time of one function | Tells you whether a change helped, not why. |
Whichever tool you choose, build with optimizations and keep symbols so call sites are readable. Add this to Cargo.toml for profiling runs:
[profile.release]
debug = trueProfiling a debug build misleads you. Without optimization, iterator chains and inlined helpers allocate and call differently from release code, and you would be fixing problems that do not exist in production.
Using the `dhat` crate
Add dhat as a dependency, then install its allocator and start a profiler at the top of main. When the Profiler value is dropped at the end of main, it writes dhat-heap.json, which you open in the DHAT viewer.
#[global_allocator]
static ALLOC: dhat::Alloc = dhat::Alloc;
fn main() {
let _profiler = dhat::Profiler::new_heap();
let words: Vec<String> = (0..10_000).map(|i| format!("word-{i}")).collect();
println!("{}", words.len());
}The viewer ranks allocation sites by total bytes, by number of blocks, and by peak usage. Two columns are worth reading first:
- Total blocks at a site. A high count with a small size points to per-item allocations, such as
format!in a loop. Later chapters show how to remove these. - Lifetime. Blocks freed almost immediately after allocation are the best candidates for buffer reuse or borrowing.
Reading the numbers
After a change, compare the same workload before and after, and check these things:
- Allocations per unit of work. Divide by the number of items or requests. "Allocations per line" is easier to reason about than a raw total.
- Bytes, not just count. Replacing many small allocations with one large one can lower the count and raise memory use. Check that you can afford that.
- Time. Run a benchmark on release builds with realistic input. If the allocation count dropped and the time did not move, the change is probably not worth its complexity.
- Realistic input sizes. A trick that helps on 10,000 items may do nothing on 10. Use sizes close to production.
Common mistakes
- Measuring a debug build. Counts and timings differ from release. Always measure
--release. - Counting inside the measured closure. Calling
println!or building aStringfor logging inside the region adds allocations to the total. Print after the second read. - Forgetting
realloc. If you overridereallocwithout counting it, vector growth looks free. - Treating zero as the goal. The target is the metric you care about, not zero allocations. Some allocations are the right design.
- Optimizing before profiling. Guessing that
cloneis the problem often fixes a line that costs 0.1% of runtime.
Exercise
You wrap a function in a counting allocator and see 12 allocations per call. The function is called once at startup. Should you optimize it, and what would change your answer?
Show answer
No. An allocation cost that is paid once is almost never measurable. It would become worth optimizing if a profiler or benchmark showed the function in a hot path, for example if it were called per request or per item, or if its allocations dominated startup latency that you must reduce. Count per unit of work and confirm with a profile before changing code.
Exercise
Your counting allocator reports zero allocations for a loop that calls Vec::push many times, even though the vector clearly grows. The allocator overrides realloc to forward to System.realloc. What is the most likely bug, and how do you fix it?
Show answer
The overridden realloc does not increment the counter. Growing a Vec calls realloc, not alloc, so the growth steps go uncounted. Fix it by calling ALLOCS.fetch_add(1, Ordering::Relaxed) (and adding new_size to a byte counter if you track bytes) inside realloc before forwarding to System.realloc, or by removing the override so the default implementation calls your alloc.