How to benchmark memory usage of a function?

后端 未结 4 512
情话喂你
情话喂你 2021-01-01 14:07

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 wou

4条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-01 14:44

    Now there is jemalloc_ctl crate which provides convenient safe typed API. Add it to your Cargo.toml:

    [dependencies]
    jemalloc-ctl = "0.3"
    jemallocator = "0.3"
    

    Then configure jemalloc to be global allocator and use methods from jemalloc_ctl::stats module:

    • jemalloc_ctl::stats::allocated
    • jemalloc_ctl::stats::resident

    Here is official example:

    use std::thread;
    use std::time::Duration;
    use jemalloc_ctl::{stats, epoch};
    
    #[global_allocator]
    static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;
    
    fn main() {
        loop {
            // many statistics are cached and only updated when the epoch is advanced.
            epoch::advance().unwrap();
    
            let allocated = stats::allocated::read().unwrap();
            let resident = stats::resident::read().unwrap();
            println!("{} bytes allocated/{} bytes resident", allocated, resident);
            thread::sleep(Duration::from_secs(10));
        }
    }
    

提交回复
热议问题