Elapsed time in C

#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 get 0.000 to start and end. I do not understand the source of the error.

It is also better to use time (start) and time (end) or start = clock () and end = clock () to calculate elapsed time.

+3
source share
6 answers

In most (almost all?) Systems, time()it only has a granularity of one second, so any time intervals cannot be measured with it. If you are using Unix, try using it instead gettimeofday.

+6
source

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

+4

. () , . -:

count = 10,000,000

start = readCurrentTime()

loop count times:
    myCode()

end = readCurrentTime()

elapsedTotal = end - start
elapsedForOneIteration = elapsedTotal / count

, . :

loop count times:
    myCode()
    myCode()
and measure elapsed1 (2 x count iterations + loop overhead)

loop count times:
    myCode()
and measure elapsed2 (count iterations + loop overhead)

actualElapsed = elapsed1 - elapsed2
(count iterations -- because rest of terms cancel out)
+2

time ( ) . , .

( gprof * nix, Instruments OS X, Windows . " C Windows Eclipse" ), .

0

, , . 0 99,999,

1,00 .

0

All Articles