Instead of using the time
shell command, you should use the clock()
function defined in <time.h>
. It is far more precise with much less overhead.
Here is the modified code:
#include <stdio.h>
#include <time.h>
unsigned long int fibo(int n) {
if (n <= 1)
return 1;
else
return fibo(n - 1) + fibo(n - 2);
}
int main(void) {
unsigned long fn;
unsigned int n;
double time_in_secs;
printf("Enter an integer <= 47:\n");
if (scanf("%u", &n) == 1) {
clock_t start = clock();
fn = fibo(n);
time_in_secs = (double)(clock() - t) / CLOCKS_PER_SEC;
printf("Fibo(%u) = %lu\n", n, fn);
printf("Computation took %f secs\n", time_in_secs);
}
return 0;
}
If your are programming on an MS/DOS system, and clock()
is not available there, you could try and define it this way:
#define CLOCK_PER_SEC 18.2
#define clock() (*(unsigned long __far *)0x0040006C)
The tick interrupt (INT 8) updates a 32-bit tick counter 65536 times per hour. The 32-bit tick counter is accessible at absolute address 0040:006C
. If you want more precise timings, you can try and reprogram the interrupt controller to make it fire interrupts faster. You then need to install your own handler to filter these interrupts to avoid messing the system's tick counter.
Here is a useful site for more info about the PC/DOS system and its BIOS data: http://www.fysnet.net/rombios.htm
Also note that your Fibonacci sequence is not consistent with the classic definition fib(0) = 0, fib(1) = 1
. The Wikipedia article is here.
Here is the corresponding code:
unsigned long int fibo(int n) {
if (n <= 1)
return n;
else
return fibo(n - 1) + fibo(n - 2);
}