您可以使用 jemalloc 分配器来打印分配统计信息。例如,
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()) };
}
在单线程程序中,应该可以很好地衡量结构占用的内存量。只需在创建结构之前和之后打印统计信息并计算差异。
您还可以使用 Valgrind (Massif) 来获取堆配置文件。它与任何其他 C 程序一样工作。确保您在可执行文件中启用了调试符号(例如,使用调试构建或自定义 Cargo 配置)。例如,您可以使用 http://massiftool.sourceforge.net/ 来分析生成的堆配置文件。
(我已验证这可以在 Debian Jessie 上运行,在不同的设置中,您的里程可能会有所不同)。
(为了在 Valgrind 中使用 Rust,您可能必须切换回系统分配器)。
附:现在还有a better DHAT。
jemalloc can be told 转储内存配置文件。你可能可以用 Rust FFI 做到这一点,但我还没有研究过这条路线。