Wednesday, May 3, 2017

Sleep + GetTickCount

In this article I will discuss one of the problem that I was facing with Sleep API

I had written a small piece of code which is shown below

START OF CODE

DWORD dwCnt, dwCurTick;

dwCurTick = GetTickCount();

for(dwCnt = 0; dwCnt < 100; dwCnt++)
{
    Sleep(2); 
}

RETAILMSG (1,(L"Tick Diff:%d\r\n",GetTickCount()-dwCurTick));

END

I was expecting Tick Diff:200 since we kept Sleep(2) for hundred times. But the result is seen as 300.

When we modify the code as given below
 

START OF CODE

DWORD dwCnt, dwCurTick;

for(dwCnt = 0; dwCnt < 100; dwCnt++)
{
    dwCurTick = GetTickCount();

    Sleep(2); 
    RETAILMSG (1,(L"Tick Diff:%d\r\n",GetTickCount()-dwCurTick));
}

END

Result:Tick Diff:3 is printed for hundred times.


START OF CODE

DWORD dwCnt, dwCurTick;

dwCurTick = GetTickCount();while(GetTickCount() - dwCurTick <= 200);
RETAILMSG (1,(L"Tick Diff:%d\r\n",GetTickCount()-dwCurTick));

END
Result: Tick Diff:201

So for accurate Tick Delays use the GetTickCount API.

No comments:

Post a Comment