Crate allocation_counter
source ·Expand description
This crate provides a method to measure memory allocations while running some code.
It can be used either exploratory (obtaining insights in how much memory allocations are being made), or as a tool to assert desired allocation behaviour in tests.
Usage
Add as a dependency - since including the trait replaces the global memory allocator, you most likely want it gated behind a feature.
[features]
count-allocations = ["allocation-counter"]
[dependencies]
allocation-counter = { version = "0", optional = true }
The measure() function is now available, which can measure memory allocations made when the supplied function or closure runs.
Tests can be conditional on the feature:
#[cfg(feature = "count-allocations")]
#[test]
{
// [...]
}
The test code itself could look like:
// Verify that no memory allocations are made:
let info = allocation_counter::measure(|| {
code_that_should_not_allocate();
});
assert_eq!(info.count_total, 0);
// Let's use a case where some allocations are expected.
let info = allocation_counter::measure(|| {
code_that_should_allocate_a_little();
});
// Using a lower bound can help track behaviour over time:
assert!((500..600).contains(&info.count_total));
assert!((10_000..20_000).contains(&info.bytes_total));
// Limit peak memory usage:
assert!((100..200).contains(&info.count_max));
assert!((1_000..2_000).contains(&info.bytes_max));
// We don't want any leaks:
assert_eq!(0, info.count_current);
assert_eq!(0, info.bytes_current);
// It's possible to opt out of counting allocations
// for certain parts of the code flow:
let info = allocation_counter::measure(|| {
code_that_should_not_allocate();
allocation_counter::opt_out(|| {
external_code_that_should_not_be_tested();
});
code_that_should_not_allocate();
});
assert_eq!(0, info.count_total);
Run the tests with the necessary feature enabled.
cargo test --features count-allocations
Structs
- The allocation information obtained by a measure() call.
Functions
- Run a closure or function while measuring the performed memory allocations.
- Opt out of counting allocations while running some code.