You could use a timer event. If you need a really solid clock, you need to raise your priority level to the max. This code will give you the best possible performance for a user-mode application. I've omitted the usual error checking, for clarity, but I've marked the calls that should be checked. If in doubt, consult MSDN.
Windows timer resolution is limited to a global time-slice Windows uses to switch between threads. On modern CPUs, that value is usuallu 2-5ms. on older CPUs this value is 10-15ms. You can control this global setting
by calling timeBeginPeriod(). This will affect the precision of the interrupts.
// use this event to exit the loop, by calling SetEvent(hExitEvent).
HANDLE hExitEvent = CreateEvent(NULL, NULL, FALSE, NULL);
void RealTimeLoop()
{
// You may want to raise the process priority...
HANDLE hProcess = GetCurrentProcess(); // never fails
SetPriorityClass(hProcess, REALTIME_PRIORITY_CLASS);
// setting the priority is critical.
HANDLE hThread = GetCurrentThread(); // never fails
SetThreadPriority(hThread, THREAD_PRIORITY_TIME_CRITICAL); // could fail
timeBeginPeriod(1); // could fail
HANDLE hTimer = CreateWaitableTimer(NULL, FALSE, NULL); // could fail
// could also set a call back here, but I've never tried it.
LARGE_INTEGER dueTime = {};
SetWaitableTimer(hTimer, &dueTime, 20, NULL, NULL, FALSE); // could fail
HANDLE ah[2] = { hExitEvent, hTimer };
bool exitLoop = false;
while(!exitLoop)
{
switch (WaitForMultipleObjects(2, ah, FALSE, INFINITE))
{
default: // error would arrive here
case 0: exitLoop = true; break;
case 1: ExecuteMethod(); break;
}
}
timeEndPeriod(1);
CloseHandle(hTimer);
CloseHandle(hThread);
CloseHandle(hProcess);
}