4
#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.

Thomas Owens
  • 114,398
  • 98
  • 311
  • 431
suzy
  • 41
  • 1
  • 1
  • 2
  • 1
    This works fine for me. Have you verified the values of start and end with a debugger? (Note: to test it I put a "sleep(1)" between the time(start) and time(end).) – Tom May 30 '11 at 18:07
  • If you need time measurements at finer resolution, have you tried `clock()`? – sverre May 30 '11 at 18:08
  • 2
    @sverre: `clock()` does not measure the absolute passage of time. It measures the quantity of time spent specifically on this one process. Important distinction. If you're profiling, you may want this; otherwise you probably don't. – Lightness Races in Orbit May 30 '11 at 19:06

6 Answers6

7

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.

jwodder
  • 54,758
  • 12
  • 108
  • 124
4

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.

mhyfritz
  • 8,342
  • 2
  • 29
  • 29
2

Short excerpts of code typically don't take long enough to run for profiling purposes. A common technique is to repeat the call many many (millions) times and then divide the resultant time delta with the iteration count. Pseudo-code:

count = 10,000,000

start = readCurrentTime()

loop count times:
    myCode()

end = readCurrentTime()

elapsedTotal = end - start
elapsedForOneIteration = elapsedTotal / count

If you want accuracy, you can discount the loop overhead. For example:

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)
Ates Goral
  • 137,716
  • 26
  • 137
  • 190
0

time has (at best) second resolution. If your code runs in much less than that, you aren't likely to see a difference.

Use a profiler (such a gprof on *nix, Instruments on OS X; for Windows, see "Profiling C code on Windows when using Eclipse") to time your code.

Community
  • 1
  • 1
outis
  • 75,655
  • 22
  • 151
  • 221
0

The code you're using between the measurements is running too fast. Just tried your code printing numbers from 0 till 99,999 and I got

Elasped time is 1.00 seconds.

DallaRosa
  • 5,737
  • 2
  • 35
  • 53
0

Your code is taking less than a second to run.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055