int fib(int n,int a,int b){
if (n==2){
return a+b;
}
return fib(n-1,b,a+b);
}
int main() {
time_t begin,end;
begin = clock();
fib(10000,0,1);
end = clock();
printf("%f",difftime(end,begin));
}
int main() {
time_t begin,end;
time(&begin);
fib(10000,0,1);
time(&end);
printf("%f",(double)(end-begin)/CLOCKS_PER_SEC);
}
1)First question
Why does my first main give prints me a time 288.000000
,I'm assuming this is 288 milliseconds but in the documentation it is supposed to give me the result in seconds.I am on Mac by the way.
2)Second Question
Why does the second main.
Why does this print me the output time being 0.000000
.
I understand that time() give me a time_t structure that i put inside begin
and end
time_t
structs and then i find the difference in seconds,doesn't seem to work.
You could try something like the following approach:
Output:
The return type from
clock()
isclock_t
- not necessarily seconds. Apple : clock. Which measures the number of ticks the CPU has used (CLOCKS_PER_SEC
). This value is not necessarily milliseconds or seconds.time()
returns the number of whole seconds since a particular point in time (1/1/1970).So calling time twice in quick succession, results in the same number of whole seconds.
difftime
expectstime_t
(return type fromtime()
) as its parameters and creates an elapsed time (in seconds).Thus it is not correct to call for
clock_t
values.