Read Performance counter in Mac from terminal

Viewed 1307

I would like to know how to get performance monitoring counter measurements on a Mac. With Linux, we can use the "perf stat" command to get measurements. With a Mac it's harder. Specifically, I would like to know how I can get the number of branch mispredictions and the number of branches executed for a program running from the command line, preferably without recompiling the program. I have done some Googling but what I need is a solution; if you can show me how you brought up a terminal, typed in some command (maybe using some tool you downloaded), and got the number of mispredictions for, say /bin/ls, that would be great.

1 Answers

Official macOS tool to work with profiling, both based on software events and on hardware events (performance counters), is Instruments tool - https://help.apple.com/instruments/mac/current/. It seems to be part of XCode development tools.

This tool have some limited variants to collect profiles from command-line mode, check https://help.apple.com/instruments/mac/current/#/devb14ffaa5

https://help.apple.com/instruments/mac/current/#/devba105ecc

Launch Instruments from the command line

You can use the open command to launch any app in OS X via Terminal, including Instruments.

Launch Terminal (in /Applications/Utilities/).

Run the following command:

open /Applications/Xcode.app/Contents/Applications/Instruments.app

The Instruments app launches.

Note: You can also use either of two command-line utilities to profile an app without actually displaying the Instruments user interface.

instruments — This utility profiles an app using a specified template. The results can be saved to a file and then manually opened in the main Instruments app for viewing and analysis. To learn more, go to Profile with the instruments command-line tool.

To get IPC or branches, use GUI to create profile with usage of counters usage (1 or 2) and save it as template, and then use CLI tool instruments to collect trace data. Trace file can be viewed with Instruments GUI; there was incomplete attempt to decode that files.

The page https://medium.com/@pavelkucera/counting-branch-mispredictions-on-macos-7397ae8c5b51 also lists another variant to work with hardware counters on macOS, the https://github.com/opcm/pcm project:

You first have to build the tool, but then it is easy to use:

run pmu-query.py
enter “BR_INST_RETIRED.NOT_TAKEN”, the result should be similar to: cpu/umask=0x10,event=0xC4,name=BR_INST_RETIRED.NOT_TAKEN/
run ./pcm-core.x -e event where “event” stands for the result from the previous step

This gives you continuous results for all the running processes. Find info on how to profile a single process in ./pmc-core.x --help

The good news is that results are easily readable as they can be output as csv file. The bad news is that profiling a single process still includes activity from other processes.

Related