old-old-netflux-blog/content/posts/rust-cpu-profiling.md

2.9 KiB

title date draft tags
CPU profiling in Rust 2020-06-24T16:37:30+02:00 false
coding
rust

Recently I've been hacking with Rust's recently-stabilized async/await support, and especially trying to understand how suitable it will be for building real-time audio stuff on top of. More on this topic soon I hope, but during the exploration process I discovered a nice bit of Rust tooling to share.

A key requirement of both real-time and audio software is of course performance. Habitually I keep htop or one of its Rusty cousins running in a separate tmux pane to expose general performance characteristics such as CPU usage immediately, but after identifying a general problem it's usually necessary to dive deeper and understand exactly which function calls in a particular program are the culprit(s).

Flamegraph is a crate that generates SVG diagrams, known as flamegraphs, that analyze a program's stack activity and visualizes it in a format that makes it easy to identify the stack frames (typically function calls) that a program is spending the most time in. It's neither particularly high tech stuff - flamegraphs are typically generated by triggering a periodic interrupt and building a chronological picture of the makeup of the stack - nor an exact science. But generally if your program is exhibiting poor performance then analyzing stack activity is a good place to start, and flamegraphs make the experience much prettier.

Note that flamegraphs were originally invented by Brendan Gregg who has a great writeup and a number of other resources available here. It's also worth noting that although flamegraphs are a relatively new method of visualising stack activity, the underlying approach is widely seen in other platforms - and popularly in Chrome DevTools's "timeline" tab.

Flamegraphs in Rust

This brings us to the cargo-flamegraph crate, which is a piece of Cargo tooling to allow trivial CPU profiling of Rust binaries1. It in turn depends heavily on a second crate, Inferno, to generate the actual graphs from raw dtrace data.

First step is to install using Cargo:

cargo install flamegraph

I also had to install some other dependencies:

sudo apt-get install -y linux-tools-common linux-tools-generic

as well as some kernel version-specific packages:

# Note: may not be necessary on other kernel versions
sudo apt-get linux-tools-5.3.0-59-generic linux-cloud-tools-5.3.0-59-generic

  1. Or any other binary for that matter, but I'm mostly interested in profiling binaries that I build using Rust. ↩︎