This creates what is called an instrumented executable. It contains additional code which records the time spent in each function.

Warning

If gprof does not appear to produce any output, it may be because of a bug in GCC versions 5 and 6. As a workout, provide the additional flag -no-pie to compilation and linking. Make sure there is only one hyphen at the start of the argument (NOT –no-pie).

When run, the program will produce a file gmon.out in the same directory as it is run. You can pass your program to gprof to display the profiling results:

You can see above that approximately 60% of the time was spent calculating the Fibonacci sequence, while 30% was spent looping 100 million times. If this was a real life scenario, you could now start to optimise your code!

If you find text hard to analyze, see the gprof2dot section below on how to create a visualization of the above results.

The above command will write the profiling results to the terminal. Instead, if you wish to write the results to a file, use the following command:

$ gprof profiling_test > profiling_results.txt

Clean Exiting

gmon.out is only written to if your C/C++ program exits cleanly, that is, it either calls exit() or returns from main().

Here is the relevant info from the gprof manual:

The profiled program must call "exit"(2) or return normally for the profiling information to be saved in the gmon.out file.

Your program doesn’t count as a clean exit if it is running in a Linux terminal and Ctrl-C is pressed! However, there is a way to fix this, by catching the Ctrl-C signal and writing to the file before exiting&mldr;