How to profile C/C++ code using gprof

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:

  1. Make sure your C or C++ code compiles without errors. Make sure your compiled program starts, executes and exits without any errors.
  2. Add the -pg option to both the object compilation and linking stages of the program compilation. Compile the program from scratch.
  3. 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.
    $ ./foo
  4. 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

3 thoughts on “How to profile C/C++ code using gprof

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.