如何对函数的内存使用情况进行基准测试? [英] How to benchmark memory usage of a function?

查看:81
本文介绍了如何对函数的内存使用情况进行基准测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到Rust的测试有一个基准模式,可以在ns/iter中测量执行时间,但是我找不到测量内存使用情况的方法.

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).

我发现了此问题,它要求完全相同的内容.

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

推荐答案

您可以使用jemalloc分配器来打印分配统计信息.例如,

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

Cargo.toml:

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:

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.

您还可以使用Valgrind( Massif )获取堆配置文件.它与任何其他C程序一样工作.确保在可执行文件中启用了调试符号(例如,使用调试版本或自定义Cargo配置).您可以使用 http://massiftool.sourceforge.net/来分析生成的堆配置文件.

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.

(我验证了此功能可用于Debian Jessie,但在不同的设置下,您的行驶里程可能会有所不同.)

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

(为了将Rust与Valgrind结合使用,您可能必须切换回系统分配器).

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

P.S.现在也有更好的DHAT .

jemalloc 可以被告知以转储内存轮廓.您可能可以使用Rust FFI做到这一点,但是我还没有研究这条路线.

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.

这篇关于如何对函数的内存使用情况进行基准测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆