Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

elapsed time in C

Tags:

c

time

elapsed

#include <time.h> 
time_t start,end; 
time (&start);
//code here
time (&end); 
double dif = difftime (end,start); 
printf ("Elasped time is %.2lf seconds.", dif ); 

I'm getting 0.000 for both start and end times. I'm not understanding the source of error.

Also is it better to use time(start) and time(end) or start=clock() and end=clock() for computing the elapsed time.

like image 861
suzy Avatar asked Dec 12 '22 12:12

suzy


2 Answers

On most (practically all?) systems, time() only has a granularity of one second, so any sub-second lengths of time can't be measured with it. If you're on Unix, try using gettimeofday instead.

like image 191
jwodder Avatar answered Dec 21 '22 23:12

jwodder


If you do want to use clock() make sure you understand that it measures CPU time only. Also, to convert to seconds, you need to divide by CLOCKS_PER_SEC.

like image 33
mhyfritz Avatar answered Dec 21 '22 23:12

mhyfritz