C++ 可等待的计时器不精确

C++ 可等待的计时器不精确,c++,windows,winapi,mfc,C++,Windows,Winapi,Mfc,我在实际的生产代码中使用了以下代码的一个版本。它为将来的一段时间设置一个可等待的计时器,然后有一个工作线程等待它启动: //Create timer hWTimer = ::CreateWaitableTimer(NULL, FALSE, NULL); //Number of minutes to wait int nMinutesToWait = 5; //Predict when it should fire COleDateTime dtWhen = COleDateTime::Get

我在实际的生产代码中使用了以下代码的一个版本。它为将来的一段时间设置一个可等待的计时器,然后有一个工作线程等待它启动:

//Create timer
hWTimer = ::CreateWaitableTimer(NULL, FALSE, NULL);

//Number of minutes to wait
int nMinutesToWait = 5;

//Predict when it should fire
COleDateTime dtWhen = COleDateTime::GetCurrentTime() + COleDateTimeSpan(0, 0, nMinutesToWait, 0);

//Set timer
SetWaitableTimerSecondsFromNow(hWTimer, nMinutesToWait * 60);

//Waiting part
if(::WaitForSingleObject(hWTimer, INFINITE) == WAIT_OBJECT_0)
{
    //Timer has fired, compare when
    _TRACE(L"Time scheduled for: %s, time fired: %s", 
        dtWhen.Format(),
        COleDateTime::GetCurrentTime().Format());
}

BOOL SetWaitableTimerSecondsFromNow(HANDLE hWTimer, double fSecs2Wait)
{
    //INFO: I'm setting the timer to a relative time to ensure that it
    //      doesn't fire in case the system clock is adjusted.
    LARGE_INTEGER li;
    li.QuadPart = -10000000LL * (LONGLONG)fSecs2Wait;   //Convert to 100 nanosecond intervals (MUST BE NEGATIVE)
    if(li.QuadPart >= 0)
        return FALSE;

    return ::SetWaitableTimer(hWTimer, &li, 0, NULL, NULL, FALSE);
}
它工作得很好,在大多数情况下,计时器需要启动的时间和它实际启动的时间是100%匹配的。但很少,计时器提前10-15秒触发,只需等待5分钟。似乎这个问题主要发生在Windows XP上


有人知道这里发生了什么以及如何缓解吗?

这不太可能是您问题的根源,但您确定这样做符合您的要求吗<代码>-10000000LL*(长)fSecs2Wait如果你要求,比如说,“5.1秒”,它只会等待5秒,因为你在乘法之前截断到
long
。似乎您更希望执行
(LONGLONG)(-10000000.*fsecs2Wait)@JoeZ:好的,说得好。但它不会把时间缩短到10-15秒。我在日志文件中看到了这些差异。是否可能是因为当时系统太忙(例如,CPU使用率高,或者由于任务切换而陷入困境),以至于等待的线程没有很快获得时间片?@JimMischel:IDK,但只有5分钟!