views:

97

answers:

2

Hello,

I try to call a function every 1 ms. The problem is, I like to do this with windows. So I tried the multimediatimer API.

Multimediatimer API

Source

idTimer = timeSetEvent( 
     1, 
     0,
     TimerProc, 
     0, 
     TIME_PERIODIC|TIME_CALLBACK_FUNCTION ); 

My result was that most of the time the 1 ms was ok, but sometimes I get the double period. See the little bump at around 1.95ms multimediatimerHistogram

My first thought was that maybe my method was running too long. But I measured this already and this was not the case.

Queued Timers API

My next try was using the queud timers API with

hTimerQueue = CreateTimerQueue();
if(hTimerQueue == NULL)
{
printf("Error creating queue: 0x%x\n", GetLastError());
}

BOOL res = CreateTimerQueueTimer(
&hTimer, 
hTimerQueue, 
TimerProc, 
NULL, 
0, 
1,  // 1ms
    WT_EXECUTEDEFAULT);

But also the result was not as expected. Now I get most of the time 2 ms cycletime. queuedTimer

Measurement

For measuring the times I used the method QueryPerformanceCounter and QueryPerformanceFrequency.

Question

So now my question is if somebody encountered similar problems under windows and maybe even found a solution?

Thanks.

+5  A: 

Without going to a real-time OS, you cannot expect to have your function called every 1 ms.

On Windows that is NOT a real-time OS (for Linux it is similar), a program that repeatedly read a current time with microsecond precision, and store consecutive differences in an histogram have a non-empty bin for >10 ms! This means that sometimes you will have 2 ms, but you can also get more between your calls.

Didier Trosset
What exactly do you mean with hava a non-empty bin for > 10ms? Do you mean that getting the time takes more than 10ms?
schoetbi
That is correct. Doing nothing but calling twice a function to get time results in a time difference above 10 ms. Very rare, one time every minute or hour depending on the actual computer, but happens!
Didier Trosset
A: 

You can try to run timeBeginPeriod(1) at the program start and timeEndPeriod(1) before quitting. This probably can enhance timer precision.

n0rd
Not on my machine. Thanks anyway:-)
schoetbi