Rust perf cpu 和内存

perf cpu

  • Cargo.toml 增加如下参数
1
2
[profile.release]
debug = true

并且以 release 模式运行代码

  • 安装 perf + FlameGraph
1
2
sudo pacman -Syu perf
git clone https://github.com/brendangregg/FlameGraph.git
  • 开抓
1
2
3
4
5

sudo perf record --call-graph dwarf -p 进程id
sudo perf script > out.perf
FlameGraph/stackcollapse-perf.pl out.perf > out.folded
FlameGraph/flamegraph.pl out.folded > out.svg

注:一定要是 sudo 来抓,不然抓不到系统调用

perf memory

  • Cargo.toml 增加如下参数
1
2
[profile.release]
debug = true
  • 内存分配器替换

Cargo.toml 增加依赖

1
2
3
4
5
6
7
[dependencies]
jemallocator = "0.3.2"
jemalloc-ctl = "0.3.2"

[dependencies.jemalloc-sys]
version = "0.3.2"
features = ["stats", "profiling", "unprefixed_malloc_on_supported_platforms"]

main.rs 替换 allocator

1
2
#[global_allocator]
static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;
  • 在运行 rust 程序的窗口设置环境变量
1
export MALLOC_CONF="prof:true,lg_prof_interval:26"
  • 分析 heap

代码运行起来之后,就会看到在运行目录产生了很多 jeprof.x.x.x.heap 文件,以下面为例,我们以程序最开始运行生成的 heap 作为基准,拿到生成的第 279 个文件进行比较,之后就可以打开 a.pdf 查看了

1
jeprof -pdf ./target/release/mencius-server --base=jeprof.583543.0.i0.heap jeprof.583543.279.i279.heap> a.pdf

pdf 里可以比较直观的展示出来内存分配释放最多的地方,这里便是你可以进行优化的地方

总结

这里仅仅是简单介绍下最近 perf cpu 和 memory 用到的工具,如果需要会补充更详细的内容,比如如何看 cpu 火焰图,还有如何看 cpu 使用情况

Author: suikammd
Link: https://www.suikammd.com/2022/12/06/rust_perf_cpu_and_memory/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.