Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to install gprof on OS X

I'm trying to use gprof to profile a c++ application I've written but I can't figure out for the life of me how to download and install it. I've googled everything I can think of and can't even find a download link. Someone please help!

like image 769
zaloo Avatar asked Mar 25 '14 01:03

zaloo


2 Answers

It seems there are two components to gprof. One is a part of the GCC compiler itself, invoked by using the -pg argument. The other is the gprof command, which apparently is part of GNU binutils. I'll leave it to you to figure out how to install GCC and binutils on OSX...

like image 119
feuGene Avatar answered Oct 08 '22 06:10

feuGene


I did not find a MacOS solution for gprof and gcov did not work for me, but gperftools (Google Performance Tools) do work. Here is how to install them on MacOS:

brew install google-perftools graphviz ghostscript gv
brew link --overwrite ghostscript

Next, run the profiler on a program:

CPUPROFILE=program_name.prof DYLD_INSERT_LIBRARIES=/usr/local/Cellar/gperftools/2.6.3/lib/libprofiler.dylib ./program_name
pprof --pdf program_name program_name.prof > program_name.pdf

You can find more options for gperftools here. Finally, open the program_name.pdf file in a PDF viewer such as Preview to enjoy the fancy graphviz output.

Obviously, running the profiler on a program can be automated very easily with a Bash script, as there only is the one program_name parameter and the shared library location is constant. Here is an example script called profile.sh that does exactly that, but includes compiling and adds a second variable so that you can compile .cpp files with a different name:

#!/bin/bash
g++-7 -fopenmp -O3 -o $1 $2.cpp
CPUPROFILE=$1.prof DYLD_INSERT_LIBRARIES=/usr/local/Cellar/gperftools/2.6.3/lib/libprofiler.dylib ./$1
pprof --pdf $1 $1.prof > $1.pdf
echo "Profiling results: $1.pdf"

Next, modify the permissions so it can run from any folder:

chmod +x profile.sh

The script can be invoked from the command line as follows, automating the full process:

./profile.sh program_name cpp_name

You may want to separate the compilation and profiling steps, which is easy enough to do by removing the g++-7 line in the shell script.

like image 42
Adam Erickson Avatar answered Oct 08 '22 06:10

Adam Erickson