Rust CPU and Memory Profiling

CPU Profiling with perf

  • Add the following settings to Cargo.toml
1
2
[profile.release]
debug = true

Also run the code in release mode.

  • Install perf + FlameGraph
1
2
sudo pacman -Syu perf
git clone https://github.com/brendangregg/FlameGraph.git
  • Start profiling
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

Note: You must use sudo to profile; otherwise, system calls cannot be captured.

Memory Profiling

  • Add the following settings to Cargo.toml
1
2
[profile.release]
debug = true
  • Replace the memory allocator

Add the following dependencies to 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"]

Replace the allocator in main.rs.

1
2
#[global_allocator]
static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;
  • Set the environment variable in the window where the Rust program is running
1
export MALLOC_CONF="prof:true,lg_prof_interval:26"
  • Analyze the heap

Once the code is running, you will see many jeprof.x.x.x.heap files generated in the working directory. In the example below, we use the heap generated when the program first started as the baseline and compare it with the 279th generated file. You can then open a.pdf to view the results.

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

The PDF clearly shows where the most memory is allocated and freed. These are the areas you can optimize.

Summary

This is only a brief introduction to the tools I recently used for CPU and memory profiling. If needed, I will add more details, such as how to read CPU flame graphs and how to inspect CPU usage.

Author: suikammd
Link: https://suikammd.github.io/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.