tags:

views:

87

answers:

3

i have a own GetTickCount() function returning an unsigned int (the count rolls over to zero on 0xFFFFFFFF)

i cant measure an elapsed time with:

unsigned int elapsed;
unsigned int start = GetTickCount();
LongOperation();
unsigned int stop = GetTickCount();

if (stop >= start )
   elapsed = stop - start;
else
   elapsed = (INT_MAX - start) + stop;

is this the same if i do a cast to signed (the time span i measure is always less than what can be represented in a signed integer - i think about 24 days) ? :

int start = (int)GetTickCount();
LongOperation();
int elapsedTime = (int)GetTickCount() - start;

if i look at the .net Environmet.TickCount property:

TickCount will increment from zero to Int32..::.MaxValue for approximately 24.9 days, then jump to Int32..::.MinValue, which is a negative number, then increment back to zero during the next 24.9 days.

so when i cast my GetTickCount() function to a signed integer i should get the behaviour from .net (wrapping occurs on 0x7FFFFFFF->0x80000000) ?

with this should be possible do measure the elapsed time as follow (seen in another post):

int start = Environment.TickCount; 
DoLongRunningOperation(); 
int elapsedTime = Environment.TickCount - start; 
A: 

In C++, if you stick with unsigned, the code will work:

unsigned int start = gettickcount();
DoLongRunningOperation();
unsigned int elapsedTime = static_cast<unsigned int>(gettickcount()) - start;

The reason you want to stick with unsigned is that unsigned arithmetic is required to use modulo arithmetic which is what you want in this case.

R Samuel Klatchko
A: 

I'm not sure GetTickCount() is the preferred function to your problem.

Can't you just use QueryPerformanceFrequency()? There's a nice example at http://msdn.microsoft.com/en-us/library/ms644904%28v=VS.85%29.aspx

Simone
+1  A: 

The prototype for GetTickCount() in C++ in Windows is: DWORD WINAPI GetTickCount(void);

So I would code it like this (similar to the other answers):

DWORD start = GetTickCount();
dosomething();
DWORD elapsed = GetTickCount() - start;

Will measure elapsed times up to the maximum number DWORD can represent.

As others have said, with unsigned arithmetic you don't need to worry about the counter wrapping around - try it yourself...

Also check GetTickCount64 and QueryPerformanceCounter/QueryPerformanceFrequency. GetTickCount64 will allow you to measure longer intervals but it is not supported on all versions of Windows while QueryPerformanceCounter allows you to measure to much higher resolution and accuracy. For example, on some windows versions GetTickCount() may only be accurate to about 18ms while QueryPerformanceCounter will be better than 1us.

Guy