Note: This how-to was made for use on a Macbook. I believe it should work as intended on Linux as well, but some changes will need to be made - especially with regard to opening Firefox automatically.
If you're not familiar with cargo-flamegraph
, or flamegraphs in general, I'd recommend taking a look at this documentation.
- You must have cargo installed
- You must have Google Chrome installed
- You should add the following script to your
~/.bashrc
or~/.zshrc
or otherrc
file. I would recommend reading through this file and making sure you understand what it does.flamegraph
requires sudo because it relies ondtrace
which relies on sudo for... reasons.
flame() {
# you should modify these two directories to your liking
OUT_DIR="${PWD}/flamegraphs"
CRATES_DIR="${HOME}/Documents/work"
# help info
# displayed when flame is run with no arguments, or when the --help flag is passed
if [ -z $1 ] || [ "$1" = "--help" ]
then
echo "flame is a little command line utility that creates and opens a flamegraph for a given rust crate."
echo "USAGE:"
echo "\tflame [crate] [args...]"
echo "\nARGS:"
echo "\t<crate>\t\t📦 the name of the crate located at ${CRATES_DIR}"
echo "\t<args>\t\t🗣️ the args to pass to your crate"
return
fi
# check if cargo-flamegraph is installed
which flamegraph >/dev/null
HAS_FLAMEGRAPH=$?
# installs flamegraph if it is not detected on your machine
if [ $HAS_FLAMEGRAPH -eq 1 ]
then
echo "installing cargo-flamegraph"
cargo install flamegraph
fi
mkdir -p ${OUT_DIR}
CRATE_NAME="$1"
CMD="$2"
ARGS="${@:3}"
CRATE_PATH="${CRATES_DIR}/${CRATE_NAME}"
# this builds your crate with the release flag and debug annotations turned on
RUSTFLAGS=-g cargo build --release --manifest-path "${CRATE_PATH}/Cargo.toml"
TIME=$(date -u +%s)
FILENAME="${OUT_DIR}/${CRATE_NAME}_${CMD}_${TIME}.svg"
# sudo is required for ...reasons
sudo flamegraph -o $FILENAME "${CRATE_PATH}/target/release/${CRATE_NAME} ${CMD} ${ARGS}"
# check if mac or linux
which open >/dev/null
HAS_OPEN=$?
which xdg-open >/dev/null
HAS_XDG_OPEN=$?
FILE_URL="file://${FILENAME}"
if [ $HAS_OPEN -eq 0 ]
then
open -a "Google Chrome" $FILE_URL
elif [ $HAS_XDG_OPEN -eq 0 ]
then
xdg-open $FILE_URL
else
echo "Could not open generated flamegraph because neither open or xdg-open are installed on this machine"
echo "You can visit ${FILE_URL} in your browser to view the flamegraph"
fi
}
You should then run exec zsh
or exec bash
in your terminal and be able to run flame wrangler build
or flame wrangler preview --headless
and it should then generate an svg file at ./flamegraphs
and open it in your browser.