Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to benchmark memory usage of a function?

Tags:

I notice that Rust's test has a benchmark mode that will measure execution time in ns/iter, but I could not find a way to measure memory usage.

How would I implement such a benchmark? Let us assume for the moment that I only care about heap memory at the moment (though stack usage would also certainly be interesting).

Edit: I found this issue which asks for the exact same thing.

like image 556
llogiq Avatar asked Jun 16 '15 13:06

llogiq


People also ask

How do you measure memory usage?

Check Computer Memory Usage EasilyTo open up Resource Monitor, press Windows Key + R and type resmon into the search box. Resource Monitor will tell you exactly how much RAM is being used, what is using it, and allow you to sort the list of apps using it by several different categories.

How do I check memory utilization in Python?

You can use it by putting the @profile decorator around any function or method and running python -m memory_profiler myscript. You'll see line-by-line memory usage once your script exits.

Which profiling will analyze the memory usage of the application?

When the Diagnostic Tools window appears, choose the Memory Usage tab, and then choose Heap Profiling.


1 Answers

You can use the jemalloc allocator to print the allocation statistics. For example,

Cargo.toml:

[package] name = "stackoverflow-30869007" version = "0.1.0" edition = "2018"  [dependencies] jemallocator = "0.3" jemalloc-sys = {version = "0.3", features = ["stats"]} libc = "0.2" 

src/main.rs:

use libc::{c_char, c_void}; use std::ptr::{null, null_mut};  #[global_allocator] static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;  extern "C" fn write_cb(_: *mut c_void, message: *const c_char) {     print!("{}", String::from_utf8_lossy(unsafe {         std::ffi::CStr::from_ptr(message as *const i8).to_bytes()     })); }  fn main() {     unsafe { jemalloc_sys::malloc_stats_print(Some(write_cb), null_mut(), null()) }; } 

In a single-threaded program that should allow you to get a good measurement of how much memory a structure takes. Just print the statistics before the structure is created and after and calculate the difference.


You can also use Valgrind (Massif) to get the heap profile. It works just like with any other C program. Make sure you have debug symbols enabled in the executable (e.g. using debug build or custom Cargo configuration). You can use, say, http://massiftool.sourceforge.net/ to analyse the generated heap profile.

(I verified this to work on Debian Jessie, in a different setting your mileage may vary).

(In order to use Rust with Valgrind you'll probably have to switch back to the system allocator).

P.S. There is now also a better DHAT.


jemalloc can be told to dump a memory profile. You can probably do this with the Rust FFI but I haven't investigated this route.

like image 87
ArtemGr Avatar answered Oct 05 '22 13:10

ArtemGr