Use a profiler
Example code
Code:
#include <stdio.h>
#include <stdlib.h>
int factorial ( int n ) {
int result = 1;
for ( ; n > 0 ; n-- ) result *= n;
return result;
}
int fibonacci ( int n ) {
if ( n == 0 || n == 1 ) return 1;
return fibonacci(n-1) + fibonacci(n-2);
}
int work ( int n ) {
int i, result = 0;
for ( i = 0 ; i < n ; i++ ) result += i;
return result;
}
int do_work ( int n ) {
int i, result = 0;
for ( i = 0 ; i < n ; i++ ) result += work(i);
return result;
}
int main ( ) {
int i;
for ( i = 1 ; i < 13 ; i++ ) {
printf( "%d %d %d %d\n", i, factorial(i), fibonacci(i), do_work(i) );
}
return 0;
}
Use these commands to compile and run the program
Code:
gcc -pg hello.c
./a.out
gprof
The output of the gprof command is quite verbose, so it's best to redirect it to a file. It also has a whole bunch of options for getting different views of the profile information.
Here's a snippet of the data I get from this simple program
[tt] % cumulative self self total
time seconds seconds calls Ts/call Ts/call name
0.00 0.00 0.00 78 0.00 0.00 work
0.00 0.00 0.00 12 0.00 0.00 do_work
0.00 0.00 0.00 12 0.00 0.00 factorial
0.00 0.00 0.00 12 0.00 0.00 fibonacci
granularity: each sample hit covers 4 byte(s) no time propagated
index % time self children called name
0.00 0.00 78/78 do_work [2]
[1] 0.0 0.00 0.00 78 work [1]
-----------------------------------------------
0.00 0.00 12/12 main [11]
[2] 0.0 0.00 0.00 12 do_work [2]
0.00 0.00 78/78 work [1]
-----------------------------------------------
0.00 0.00 12/12 main [11]
[3] 0.0 0.00 0.00 12 factorial [3]
-----------------------------------------------
1192 fibonacci [4]
0.00 0.00 12/12 main [11]
[4] 0.0 0.00 0.00 12+1192 fibonacci [4]
1192 fibonacci [4]
-----------------------------------------------
[/tt]
All the times are zero in this short example program, but in something more substantial, you'll see some positive results.
It takes a bit of time to get used to interpreting the information, so its a good idea to practice on code which is obvious - like it's obvious that main calls each function 12 times.
You can see from the code that fibonacci() is heavily recursive, and this shows up in the profile data with large numbers in comparison to the number of times everything else is being called.
--