Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use KCachegrind and Callgrind to measure only parts of my code?

I want to use valgrind to analyze my code. The problem is, that I have a huge startup sequence which I'm not interested in.

I found defines in the valgrind/callgrind.h that should help me:

  • CALLGRIND_START_INSTRUMENTATION
  • CALLGRIND_STOP_INSTRUMENTATION
  • CALLGRIND_DUMP_STATS

According to this article I have to execute valgrind with the following options:

valgrind --tool=callgrind --instr-atstart=no ./application

When I do this two files are created:

  • callgrind.out.16060
  • callgrind.out.16060.1

I then want to use kcachegrind to visualize my results. This works great but the makros for the skipping of my startup-sequence seem to do nothing. What do I have to do to measure the performance only in places where I want to?

like image 992
FrozenTarzan Avatar asked Nov 21 '22 03:11

FrozenTarzan


1 Answers

Let's assume you have the following open-source program:

int main()
{
    function1();

    function2();
    
    return 0;
}

Let's assume you want to execute Callgrind on only function2().

One approach is to insert Callgrind macros around function2(), and do the recompilation of the program (please compare with the above):

#include <valgrind/callgrind.h>
int main()
{
    function1();

    CALLGRIND_START_INSTRUMENTATION;
    CALLGRIND_TOGGLE_COLLECT;
        function2();
    CALLGRIND_TOGGLE_COLLECT;
    CALLGRIND_STOP_INSTRUMENTATION;

    return 0;
}

In some cases, callgrind.h may not be found, see here for a similar problem. The likely solution is to install/compile valgrind-devel, see this answer.

Finally, you will need to add two new options to your callgrind commands, e.g.:

valgrind --tool=callgrind \
    --collect-atstart=no --instr-atstart=no \ #new options
    <program>

This answer is an extension of this entry.

like image 159
Herpes Free Engineer Avatar answered Nov 23 '22 18:11

Herpes Free Engineer