How much memory are my objects using?

I am currently looking into rewriting an existing rather slow Python3 email analysis application using Rust. One of things that I log in my current application is how large various memory objects are (to help the admins know if they need to increase the RAM on the Virtual Machine that runs the app), using a recursive sizeof similar to the one at Compute Memory footprint of an object and its contents « Python recipes « ActiveState Code. It is an approximation of the bytes used, but it is good enough.

If I create a Vector of Structs (e.g. email sender, recipient, and subject), then look at vec.len or vec.capacity, I always get a sizes related to the type in the struct, not the actual memory being used. Is there a Rust function or crate which will help me find the total memory in use?

(EDIT: In case it is relevant, currently using Rust 1.4.0 on OS X, but live app will be rebuilt for Linux)

Thank you.

1 Like

Sounds like you want mem::size_of to get the size of a single structure. However the function isn't recursive so if the object does any allocations, those would have to be taken into account separately.

use std::mem;

struct test
{
    child : Box<[u64; 16]>
}

fn main() {
    println!("test size: {}", mem::size_of::<test>());
    println!("array size: {}", mem::size_of::<[u64;16]>());
}

In the above example the size of test is only 8 bytes, but the memory it's pointing to is 128 bytes. So a total of 134 bytes are actually used.

2 Likes

Servo is using the heapsize crate to measure the size of heap allocations during program execution. See the profiler code for how this hooks in with the actual program.

6 Likes