Valgrind is an Open Source tool for Linux that serves various functionalities ranging from memory leak detection to CPU profiling.
Easiest way to install valgrind is executing the command "sudo apt-get install valgrind" in terminal. However, since Ubuntu directories may be outdated, the installed version of Valgrind may be problematic and may throw "Unknown Command" error when you try to run it.
If you are planning to profile whole program you do not need to add anything to your source code.
If you are planning to profile a segment of the program however, you need to add the following lines to your code. Instructions can be found here
Afterwards, compile your code as usual. Make sure that you choose single threaded debugging option.
The sub tool of Valgrind that we are using is Callgrind.
Go to directory that you normally execute your code from
If you are profiling whole program run "sudo valgrind --tool=callgrind --dump-instr=yes --simulate-cache=yes --collect-jumps=yes <executable> [args...]", where <executable> is the name of the executable of your program and [args...] are the arguments that your executable has.
If you are profiling a specific segment of program run "sudo valgrind --tool=callgrind --dump-instr=yes --simulate-cache=yes --collect-jumps=yes --collect-atstart=no --instr-atstart=no [args...]", where is the name of the executable of your program and [args...] are the arguments that your executable has.
Valgrind collects a lot of data hence the run time of the program may slow down by 10-12 times; therefore do not terminate the program if you do not see anything happening.
If you see a "BRK SEGMENT OVERFLOW" error, you can ignore it since it is harmless and program flow continues during this error.
If there are no problems during your run, your program should terminate as expected and there should be a file named "callgrind.out.###" created. (### corresponds to a number.)
Visualizing the Results
To interact with the results in a GUI environment, we use another tool called kcachegrind.
To install, simply run "sudo apt-get install kcachegrind" from terminal.
After installing kcachegrind, run "sudo kcachegrind name_of_the_callgrind_out_file".
A window containing information related to your program should open.