To use profiling, the program must be compiled and linked with the
-qg profiling option:
We will use an called profiling_test.c (full code can be found at https://github.com/gbmhunter/BlogAssets/tree/master/Programming/ProfilingGprof):
We will then compile it with the command:
This creates what is called an instrumented executable. It contains additional code which records the time spent in each function.
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:
gmon.out is only written to if your C/C++ program exits cleanly, that is, it either calls
exit() or returns from
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
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…
dlsymto be found.
gprof2dot is a tool that can create a visualization of the gprof output. TO install
graphviz (which is needed if you are going to make “dot” graphs like below):
To create a dot graph image:
This created the below image for the example code above:
This work is licensed under a Creative Commons Attribution 4.0 International License .
- GCC Compiler Optimisation Levels
- MPLAB XC Compilers
- Compiling FreeRTOS With C++
- GCC Compiler Errors And How To Fix Them
- December 2018 Updates