Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to profile C/C++ code using gprof

📅 2013-Jun-24 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ gprof, profiler ⬩ 📚 Archive

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