views:

1418

answers:

3

I'm writing a portable Socket class that supports timeouts for both sending and receiving... To implement these timeouts I'm using select().... But, I sometimes need to know how long I was blocked inside select() which of course on Linux I would implement by calling gettimeofday() before and after I call select() and then using timersub() to calculate the delta...

Given that select() on Windows accepts struct timeval for it's timeout, what method should I used to replace gettimeofday() on Windows?

+1  A: 

How about:

unsigned long start = GetTickCount();
// stuff that needs to be timed
unsigned long delta = GetTickCount() - start;

GetTickCount() is not very precise, but will probably work well. If you see a lot of 0, 16 or 31 millisecond intervals, try timing over longer intervals or use a more precise function like timeGetTime.

What I usually do is this:

unsigned long deltastack;
int samples = 0;
float average;

unsigned long start = GetTickCount();
// stuff that needs to be timed
unsigned long delta = GetTickCount() - start;

deltastack += delta;
if (samples++ == 10)
{
   // total time divided by amount of samples
   average = (float)deltastack / 10.f;
   deltastack = 0;
   samples = 0;  
}
knight666
GetTicksCount rollover every ~45.7 days.
Shay Erlichmen
@Shay: When have you seen Windows up for over 45 days straight? OK, yes that was uncalled for...
Mark Ransom
+1  A: 

In your case I would use the platform independent std::clock

Shay Erlichmen
This function does not return an absolute time reference.
chmike
@chmike he didn't say he needs an absolute time reference
Shay Erlichmen
+1  A: 

I ended up finding this page: gettimeofday() on windows. Which has a handy, dandy implementation of gettimeofday() on Windows. It uses the GetSystemTimeAsFileTime() method to get an accurate clock.

dicroce