Profiling a program is an important step in analyzing program performance and identifying bottlenecks. A C or C++ program can be easily profiled in Linux using gprof:
Make sure your C or C++ code compiles without errors. Make sure your compiled program starts, executes and exits without any errors.
-pg option to both the object compilation and linking stages of the program compilation. Compile the program from scratch.
Execute the program as you normally do. It might take a while longer to finish due to the profiling. After the program exits, it writes a
gmon.out file with profiling information.
Invoke gprof with your program executable as input. It prints out profiling information in the form of both a flat profile and a call graph. You can pipe this to a pager or redirect it to a text file for examination.
$ gprof foo
Examining the output of gprof gives you an idea of which functions in the program are taking the most execution time. This information can be used to optimize such functions.
Tried with: Ubuntu 12.04 LTS