views:

128

answers:

5

I want to find out for how long (approximately) some block of code executes. Something like this:

startStopwatch();
// do some calculations
stopStopwatch();
printf("%lf", timeMesuredInSeconds);

How?

+2  A: 

You can use the clock method in ctime.h

Example:

clock_t start = clock();
/*Do something*/
clock_t end = clock();
float seconds = (float)(end - start) / CLOCKS_PER_SEC;
KLee1
+1: Nice and simple. However, won't you need to cast `(end - start)` to a floating point before the division if you want to get fractions of a second?
torak
@torak Yes, I think you're right, I haven't had a chance to test it though.
KLee1
Or multiply by 1.0
Martin York
Note that `clock()` measures CPU time, not wall-clock time (this may or may not be what you want).
caf
+2  A: 

You can use the time.h library, specifically the time and difftime functions:

/* difftime example */
#include <stdio.h>
#include <time.h>

int main ()
{
  time_t start,end;
  double dif;

  time (&start);
  // Do some calculation.
  time (&end);
  dif = difftime (end,start);
  printf ("Your calculations took %.2lf seconds to run.\n", dif );

  return 0;
}

(Example adapted from the difftime webpage linked above.)

Please note that this method can only give seconds worth of accuracy - time_t records the seconds since the UNIX epoch (Jan 1st, 1970).

Stephen
This gives only seconds precision. And your example actually doesn't use the `<ctime.h>`.
Dummy00001
Sorry, the 'c' was a typo - the ctime library is defined in `time.h`. And yes, it gives only seconds accuracy. Considering the poster said "approximately", I considered that enough. I will edit my answer to include the fact that it will only give seconds level of accuracy, if you wish.
Stephen
A: 

If you don't need fantastic resolution, you could use GetTickCount(): http://msdn.microsoft.com/en-us/library/ms724408(VS.85).aspx (If it's for something other than your own simple diagnostics, then note that this number can wrap around, so you'll need to handle that with a little arithmetic).

QueryPerformanceCounter is another reasonable option. (It's also described on MSDN)

A: 
Andreas Rejbrand
+1  A: 

GetTickCount().

#include <windows.h>
void MeasureIt()
{
    DWORD dwStartTime = GetTickCount();
    DWORD dwElapsed;

    DoSomethingThatYouWantToTime();

    dwElapsed = GetTickCount() - dwStartTime;

    printf("It took %d.%3d seconds to complete\n", dwElapsed/1000, dwElapsed - dwElapsed/1000);
}
selbie