Search code examples
clinuxprofilingprofilergprof

How to modify a C program so that gprof can profile it?


When I run gprof on my C program it says no time accumulated for my program and shows 0 time for all function calls. However it does count the function calls.

How do I modify my program so that gprof will be able to count how much time something takes to run?


Solution

  • Did you specify -pg when compiling?

    http://sourceware.org/binutils/docs-2.20/gprof/Compiling.html#Compiling

    Once it is compiled, you run the program and then run gprof on the binary.

    E.g.:

    test.c:

    #include <stdio.h>
    
    int main ()
    {
        int i;
        for (i = 0; i < 10000; i++) {
            printf ("%d\n", i);
        }
        return 0;
    }
    

    Compile as cc -pg test.c, then run as a.out, then gprof a.out, gives me

    granularity: each sample hit covers 4 byte(s) for 1.47% of 0.03 seconds
    
      %   cumulative   self              self     total           
     time   seconds   seconds    calls  ms/call  ms/call  name    
     45.6       0.02     0.02    10000     0.00     0.00  __sys_write [10]
     45.6       0.03     0.02        0  100.00%           .mcount (26)
      2.9       0.03     0.00    20000     0.00     0.00  __sfvwrite [6]
      1.5       0.03     0.00    20000     0.00     0.00  memchr [11]
      1.5       0.03     0.00    10000     0.00     0.00  __ultoa [12]
      1.5       0.03     0.00    10000     0.00     0.00  _swrite [9]
      1.5       0.03     0.00    10000     0.00     0.00  vfprintf [2]
    

    What are you getting?