我注意到 Rust 的测试有一个基准模式,可以测量 ns/iter
中的执行时间,但我找不到测量内存使用情况的方法。
我将如何实现这样的基准?让我们暂时假设我现在只关心堆内存(尽管堆栈的使用肯定也很有趣)。
编辑:我找到了this issue它要求完全相同的东西。
最佳答案
您可以使用 jemalloc 分配器来打印分配统计信息。例如,
Cargo.toml:
[package]
name = "stackoverflow-30869007"
version = "0.1.0"
edition = "2018"
[dependencies]
jemallocator = "0.5"
jemalloc-sys = {version = "0.5", 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 mem_print() {
unsafe { jemalloc_sys::malloc_stats_print(Some(write_cb), null_mut(), null()) }
}
fn main() {
mem_print();
let _heap = Vec::<u8>::with_capacity (1024 * 128);
mem_print();
}
在单线程程序中,应该可以很好地衡量结构占用的内存量。只需在创建结构之前和之后打印统计信息并计算差异。
(特别是“分配”的“总数:”。)
您还可以使用 Valgrind (Massif) 来获取堆配置文件。它与任何其他 C 程序一样工作。确保您在可执行文件中启用了调试符号(例如,使用调试构建或自定义 Cargo 配置)。例如,您可以使用 http://massiftool.sourceforge.net/分析生成的堆配置文件。
(我已验证这可以在 Debian Jessie 上运行,在不同的设置中,您的里程可能会有所不同)。
(为了在 Valgrind 中使用 Rust,您可能必须切换回系统分配器)。
附:现在还有a better DHAT .
jemalloc can be told转储内存配置文件。你可能可以用 Rust FFI 做到这一点,但我还没有研究过这条路线。
关于memory - 如何对函数的内存使用情况进行基准测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30869007/