#heap-memory #memory #memory-size #heap #complexity #data-structures

dyn_size_of

The library to report approximate amount of memory consumed by variables, including the memory allocated on heap

9 releases

0.4.3 Oct 2, 2024
0.4.2 Feb 24, 2024
0.4.1 Oct 26, 2023
0.4.0 Dec 5, 2022
0.1.1 Feb 25, 2022

#99 in Memory management

Download history 7896/week @ 2024-08-22 6526/week @ 2024-08-29 6865/week @ 2024-09-05 5359/week @ 2024-09-12 4777/week @ 2024-09-19 4637/week @ 2024-09-26 4783/week @ 2024-10-03 4549/week @ 2024-10-10 5292/week @ 2024-10-17 4647/week @ 2024-10-24 5877/week @ 2024-10-31 6024/week @ 2024-11-07 5326/week @ 2024-11-14 4352/week @ 2024-11-21 3970/week @ 2024-11-28 3839/week @ 2024-12-05

18,596 downloads per month
Used in 16 crates (10 directly)

MIT/Apache

11KB
182 lines

dyn_size_of is the Rust library by Piotr Beling to report approximate amount of memory consumed by variables, including the memory allocated on heap.

Examples

Simple usage

use dyn_size_of::GetSize;

let bs = vec![1u32, 2u32, 3u32].into_boxed_slice();
assert_eq!(bs.size_bytes_dyn(), 3*4);
assert_eq!(bs.size_bytes(), 3*4 + std::mem::size_of_val(&bs));

Implementing GetSize for a custom type

use dyn_size_of::GetSize;

struct NoHeapMem {
    a: u32,
    b: u8
}

// default implementation is fine for types that do not use heap allocations
impl GetSize for NoHeapMem {}

struct WithHeapMem {
    a: Vec<u32>,
    b: Vec<u8>,
    c: u32
}

// For types that use heap allocations:
impl GetSize for WithHeapMem {
    // size_bytes_dyn must be implemented and return amount of heap memory used
    fn size_bytes_dyn(&self) -> usize {
        self.a.size_bytes_dyn() + self.b.size_bytes_dyn()
    }
    // USES_DYN_MEM must be set to true
    const USES_DYN_MEM: bool = true;
}

let s = NoHeapMem { a: 1, b: 2 };
assert_eq!(NoHeapMem::USES_DYN_MEM, false);
assert_eq!(s.size_bytes_dyn(), 0);
assert_eq!(s.size_bytes(), std::mem::size_of_val(&s));

let d = WithHeapMem { a: vec![1, 2], b: vec![3, 4], c: 5 };
assert_eq!(WithHeapMem::USES_DYN_MEM, true);
assert_eq!(d.size_bytes_dyn(), 2*4 + 2*1);
assert_eq!(d.size_bytes(), 2*4 + 2*1 + std::mem::size_of_val(&d));

Dependencies

~125KB