Discover memory usage of a data structure

⚓ Rust    📅 2025-11-05    👤 surdeus    👁️ 5      

surdeus

I am implementing some data structure where the memory usage is of particular interest. Of course, I can run a program and have a look at the memory consumption with tools from the OS. But I would like to print the memory usage from the program. The data structure uses Vec (that may contain elements that have a vector, recursively) and Option, nothing else from the standard library.

I would be interested if there is a solution for this problem already. I thought of having a trait MemoryUseto accomplish this:

pub trait MemoryUse
where
    Self: Sized,
{
    fn total_size(&self) -> usize {
        size_of::<Self>() + self.heap_size()
    }
    fn heap_size(&self) -> usize;
}

impl MemoryUse for i32 {
    fn heap_size(&self) -> usize {
        0
    }
}
// and the same for all primitive types
impl<T: MemoryUse> MemoryUse for Vec<T> {
    fn heap_size(&self) -> usize {
        let self_size = self.capacity() * size_of::<T>();
        let elem_size: usize = self.iter().map(|x| x.heap_size()).sum();
        self_size + elem_size
    }
}
impl<T: MemoryUse> MemoryUse for Option<T> {
    fn heap_size(&self) -> usize {
        match self {
            Some(v) => v.heap_size(),
            None => 0,
        }
    }
}

The implementation for Vec and Option is an educated guess. I didn’t look at the implementation of those types.

Do you think these guesses are reasonable?

A typical use would be:

use MemoryUse;
fn test() {
    let mut multi_vec = Vec::with_capacity(5);
    println!("Size of empty multi_vec: {}", multi_vec.total_size());
    multi_vec.push(vec![1, 2]);
    multi_vec.push(vec![3, 4, 5]);
    println!("Size of multi_vec: {}", multi_vec.total_size());
}

which prints:

Size of empty multi_vec: 144
Size of multi_vec: 164

2 posts - 2 participants

Read full topic

🏷️ Rust_feed