Reputation: 1346
I need to find a way to trigger the execution of a C++ function at the exact millisecond periods.
I need to play a loop and run a function every 40 ms or less. But for the simplicity let's stay with 40 ms. I tried to put a Sleep(40) but the method is triggered not at exact point of time.
I am just wondering if there is another way for synchronizing actions then having a Sleep() in a endless while loop.
I tried even to play a loop at max speed (CPU went to 20%) and measuring the system time difference. Then triggering the action when 40 ms has passed.
In both cases I am experiencing delays but the worst case is that the delays are always different.
The loop is running in the thread.
I tried to give bigger priority to the thread but without success.
Additional Information
The Server is running on Windows 7 Operating System.
Upvotes: 1
Views: 3060
Reputation: 6515
You can track the time using a function such as timeGetTime:
void main()
{
unsigned int last_call_time = timeGetTime();
while(true)
{
do_something_else();
unsigned int now_time = timeGetTime();
if(now_time > (last_call_time + 40))
{
call_time_critical_function();
last_call_time = timeGetTime();//last time is re initialized
}
}
}
timeGetTime
is standard windows function that tracks the time in milliseconds. If the function is not precise enough you would have to use something that can track nanoseconds like QueryPerformanceCounter and there a lots of examples on the web on how to use this function.
Upvotes: 1