Skip to main content

Crate alloc_counter

Crate alloc_counter 

Source
Expand description

Per-thread allocation counting for tests.

Linking this crate installs a counting GlobalAlloc wrapper around System. Every test binary that uses it can then measure how many allocations a piece of code performs:

use alloc_counter::measure;

let (value, counters) = measure(|| 1u32 + 1);
assert_eq!(value, 2);
assert_eq!(counters.calls, 0);

§Per-thread counting

Counters are always on and scoped to the thread that performs the allocation. This keeps measurements exact even when the test harness runs other tests, and their bookkeeping, in parallel: an allocation made by another thread is never attributed to the measuring one. The trade-off is that only the calling thread is observed, so work that must be measured has to run on it.

measure returns the delta across a closure; counters returns a snapshot for manual before/after comparisons. The calls and bytes counters are monotonic totals of allocation requests (allocation, zeroed allocation and reallocation); live_bytes and live_allocations track memory that is still allocated and can be used to detect leaks.

The live_* gauges assume that an allocation is released by the thread that made it. Freeing on another thread changes that thread’s gauge instead, so it can go negative; scope deltas taken on a single thread are exact.

§Global allocator constraint

Rust allows a single #[global_allocator] per binary, and this crate provides one. A test binary that links alloc_counter therefore cannot also install a custom allocator (for example one that verifies zeroization). Test binaries that do not use this crate are unaffected: the allocator is only linked in when the crate is referenced.

Nothing in this crate panics. Allocations made while a thread’s counters are unavailable (during thread-local destruction) are simply not counted.

Structs§

Counters
Allocation counters for a single thread.

Functions§

counters
Returns a snapshot of the current thread’s allocation counters.
measure
Runs f and returns its result along with the allocation counters the current thread accumulated during the call.