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!
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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With