Reputation: 29
I want to measure elasped time for insertion_sort function. But, the result is 0.0000000 second. What can I do? I tried other time libraries.Unfortunatelly, it didn't... Thanks. I writed again.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int number=1;
if(number == 1)
{
struct timeval start, end;
gettimeofday(&start, NULL);
for(int i=0; i<5;i++)
{
insertion_sort( kelime, n );
}
gettimeofday(&end, NULL);
printf("Elapsed time is %.10f",(end.tv_sec * 1000000 + end.tv_usec)- (start.tv_sec * 1000000 + start.tv_usec));
}
Upvotes: 2
Views: 151
Reputation: 755026
Your calculation and printing is:
printf("Elapsed time is %.10f",
(end.tv_sec * 1000000 + end.tv_usec) -
(start.tv_sec * 1000000 + start.tv_usec));
You are trying to print an integer value with a floating point format; this is not going to lead to happiness. Assuming that the integer arithmetic does not overflow, then you can use:
printf("Elapsed time is %.6f",
((end.tv_sec * 1000000 + end.tv_usec) -
(start.tv_sec * 1000000 + start.tv_usec)) / 1000000.0);
which will give you a floating point value to print with the floating point format. There's no point in requesting 10 decimal places when gettimeofday()
supports only 6 (and 6 decimal places is the default, but explicitness is often good).
You could also use:
printf("Elapsed time is %.6f",
((end.tv_sec * 1000000.0 + end.tv_usec) -
(start.tv_sec * 1000000.0 + start.tv_usec)) / 1000000);
The key point is to make sure that enough of the computation is done in floating point arithmetic.
Upvotes: 0
Reputation: 14044
time
only has seconds granularity. Whereas your code is likely to be microseconds or milliseconds at worst. Use gettimeofday
instead which has microsecond granularity.
But note that both time
and gettimeofday
gives you wall time. If you want CPU time clock
can be used.
Upvotes: 2