Reputation: 937
The below code should find the runtime in seconds of the for loop. Looking at other resources this should do the trick, having an initial clock()
subracted from a clock()
after the for loop runs. Any ideas why the code isn't working as written?
#include <stdio.h>
#include <time.h>
//prototypes
int rfact(int n);
int temp = 0;
main()
{
int n = 0;
int i = 0;
double result = 0.0;
clock_t t;
printf("Enter a value for n: ");
scanf("%i", &n);
printf("n=%i\n", n);
//get current time
t = clock();
//process factorial 2 million times
for(i=0; i<2000000; i++)
{
rfact(n);
}
printf("n=%i\n", n);
//get total time spent in the loop
result = (double)((clock() - t)/CLOCKS_PER_SEC);
//print result
printf("runtime=%d\n", result);
}
//factorial calculation
int rfact(int n)
{
if (n<=0)
{
return 1;
}
return n * rfact(n-1);
}
Upvotes: 0
Views: 272
Reputation: 182829
result = (double)((clock() - t)/CLOCKS_PER_SEC);
This should be:
result = ((double)(clock() - t))/CLOCKS_PER_SEC;
Otherwise, you're doing integer division and converting the result to a double, which is not what you want.
Also:
printf("runtime=%d\n", result);
Should be:
printf("runtime=%f\n", result);
Upvotes: 2