#allocator #memory

allocation-counter

Count the number of memory allocation of some code

5 releases (breaking)

0.5.0 Dec 6, 2020
0.4.0 Dec 6, 2020
0.3.0 Dec 6, 2020
0.2.0 Dec 6, 2020
0.1.0 Dec 6, 2020

#181 in Memory management

Download history 19/week @ 2022-03-10 24/week @ 2022-03-17 7/week @ 2022-03-24 10/week @ 2022-03-31 42/week @ 2022-04-07 7/week @ 2022-04-14 15/week @ 2022-04-21 21/week @ 2022-04-28 43/week @ 2022-05-05 115/week @ 2022-05-12 61/week @ 2022-05-19 46/week @ 2022-05-26 57/week @ 2022-06-02 13/week @ 2022-06-09 65/week @ 2022-06-16 28/week @ 2022-06-23

174 downloads per month
Used in 2 crates

MIT/Apache

5KB

Crates.io Build

allocation-counter

Run some Rust code while counting allocations. Can be used to assert that the desired amount of memory allocations is not exceeded in tests.

It works by replacing the System allocator with a custom one which increases a thread local counter on each memory allocation before delegating to the normal system allocator.

Example 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 }

Tests can now be written to assert that the number of desired memory allocations are not exceeded:

#[cfg(feature = "count-allocations")]
#[test]
pub fn no_memory_allocations() {
    let allocations = allocation_counter::count(|| {
        code_that_should_not_allocate_memory();
    });
    assert_eq!(allocations, 0);
}

Run the tests with the necessary feature enabled:

cargo test --features count-allocations

No runtime deps