All the suggestions do in fact work, but the granularity of the time measurement is big (typically 10 to 100 milliseconds). So it actually measure something for a computation which last e.g. half a second. On current processors (running at 2 to 3Ghz, with about 3-5 instructions per cycle), that means something like a billion machine instructions executed (an "elementary step" in our C program -with an ill-defined notion of step is usually a dozen machine instructions). So your test is too small, you really should compute a million times fibionacci (10).
To be more specific the program below (where some computations are output, to avoid optimizing them all) is running in about 2 seconds. (on million computations of fibionacci of something less than 16).
#include <stdio.h>
#include <unistd.h>
#include <time.h>
long fib(int n){
if(n == 0) return 0;
if(n == 1) return 1;
return fib(n-1)+fib(n-2);
}
int main ()
{
int i=0;
int p = (int) getpid();
clock_t cstart = clock();
clock_t cend = 0;
for (i=0; i<1000000; i++) {
long f = fib(i%16);
if (i % p == 0) printf("i=%d, f=%ld\n", i, f);
}
cend = clock();
printf ("%.3f cpu sec\n", ((double)cend - (double)cstart)* 1.0e-6);
return 0;
}
The last few lines output with time ./fib
(compiled with gcc -O2 -Wall fib.c -o fib
)
are
i=936079, f=610
i=948902, f=8
i=961725, f=233
i=974548, f=3
i=987371, f=89
2.140 cpu sec
./fib 2.15s user 0.00s system 99% cpu 2.152 total
benchmarking a run smaller than about a second is not very meaningful
(and you can use the time
command to measure such a run)
See also time(7) and clock_gettime(2).