Search code examples
macossamplemacos-montereydtraceflamegraph

How to generate flamegraphs from macOS process samples?


Anyone have a clean process for converting samples on macOS to FlameGraphs?

After a bit of fiddling I thought I could perhaps use a tool such as flamegraph-sample, but it seems to give me some trouble and so I thought perhaps there may be other more up-to-date options that I'm missing insomuch that this tool gives an error:

$ sudo sample PID -file ~/tmp/sample.txt -fullPaths 1
Sampling process 198 for 1 second with 1 millisecond of run time between samples
Sampling completed, processing symbols...
Sample analysis of process 35264 written to file ~/tmp/sample.txt

$ python stackcollapse-sample.py ~/tmp/sample.txt > ~/tmp/sample_collapsed.txt

$ flamegraph.pl ~/tmp/sample_collapsed.txt > ~/tmp/sample_collapsed_flamegraph.svg
Ignored 2335 lines with invalid format
ERROR: No stack counts found

Solution

  • The following generates an appropriate 10 second sample for process ProcessName with an accompanying SVG from having FlameGraph cloned to ~/dev/macos/FlameGraph and places the outputs in ~/tmp/ with a current timestamp affixed thereunto for uniqueness and easy reference:

    sudo dtrace -x ustackframes=100 -n 'profile-10ms /execname == "ProcessName"/ { @[ustack()] = count(); } tick-10s { exit(0); }' \
    | tee ~/tmp/$(date +"%Y-%m-%d_%H.%M.%S")-ProcessName_sample.txt \
    | ~/dev/macos/FlameGraph/stackcollapse.pl \
    | ~/dev/macos/FlameGraph/flamegraph.pl \
    > ~/tmp/$(date +"%Y-%m-%d_%H.%M.%S")-WindowServer_sample.txt.svg
    

    For example, running this on WindowServer will produce the following output:

    2023-02-20_13.06.10-WindowServer_sample.txt.svg
    2023-02-20_13.06.10-WindowServer_sample.txt