Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to profile C/C++ code using Valgrind and KCacheGrind

📅 2013-Sep-17 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ kcachegrind, profiler, valgrind ⬩ 📚 Archive

Valgrind is a popular set of tools for debugging and profiling C/C++ programs. One of its tools is callgrind, which can be used to profile a program to find out which calls are taking most of the time. In addition, the profiler output can be beautifully visualized using the tool KCacheGrind.

Install

$ sudo apt-get install valgrind kcachegrind

Usage

Run the program using callgrind, you should expect this execution to be 10-100x slower:

$ valgrind --tool=callgrind ./foobar

The profiler output is written to a file named callgrind.out.XYZ, where XYZ is the process ID of this invocation. This is helpful because you can run this tool multiple times and have the profiler output of all those executions stored separately.

Open the profiler output file using KCacheGrind:

$ kcachegrind callgrind.out.XYZ

KCacheGrind displays the profiler output information in a 3-pane window. On the left is the function call list. You typically click main here. In the bottom-right pane, you see the functions called by the function you chose in the left pane (main in this case). The function which took the most time is at the top and the list is sorted accordingly. You can also view this same information in a call graph or tree map by using the Call Graph and Call Map options.

Related: How to profile using gprof and view its call graph.Tried with: Valgrind 3.7.0, KCacheGrind 0.7, Ubuntu 12.04 LTS


© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧