查询性能指标休眠问题

Query Performace Counter Sleeping Issue

本文关键字:休眠 问题 性能 查询      更新时间:2023-10-16

你好,我正试图以一定的速度循环一段代码。在这个例子中,我的目标是每秒执行代码块120次。我已经实现了这个,我用一个计数器来看看我每个周期完成了多少个循环,我得到每秒220次。这是我的代码…USERUPDATE是一个常量,它是1/120.0f, timeInterval是以纳秒为单位的USERUPDATE,我将所有的时间值转换为纳秒为sleep_for(nano())…

LARGE_INTEGER grabCpuTicks;
unsigned long long globalInterval;
unsigned long long timeInterval = (unsigned long long)(USERUPDATE*1000000000.0f);
LARGE_INTEGER cyclePerSecond;
LARGE_INTEGER ElapsedNanoSeconds;
LARGE_INTEGER PreviousNanoSeconds;
QueryPerformanceFrequency( &cyclePerSecond);
QueryPerformanceCounter(&grabCpuTicks);
PreviousNanoSeconds.QuadPart = grabCpuTicks.QuadPart;
int counter = 0;
loopTimer->setTime();

while(true)
{

    //Keyboard user input updates
    bool *keys = input->GetKeys();
    bool *mouse = input->GetClicks();
    Vector drawPos;
    double fireStrength;
    Vector temp = GetAngPos();

    if(!mouse[0] && fire && currObj != NULL)
    {
        fire = !fire;
        fireTime->setTime();
    }
    else if(mouse[0] && !fire && currObj != NULL)
    {
        Vector pos(player->GetLinPos().getx(), player->GetLinPos().gety() - 3.0f*USERHEIGHT/4.0f, player->GetLinPos().getz());
        fireStrength = fireTime->getTime()*800.0f;
        if(fireStrength > MAXSPEED)
        {
            fireStrength = MAXSPEED;
        }
        currObj = items->getNext(currObj);
        currObj->mesh->SetTrajectory(pos,GetAngPos(),fireStrength, NULL);
        fire = !fire;
    }

    //If second has passed
    if(loopTimer->getTime() >= 1.0f)
    {
        cout << "Number of loops per second: " << counter << endl;
        counter = 0;
        loopTimer->setTime();
    }
    counter++;

    QueryPerformanceCounter(&grabCpuTicks);
    ElapsedNanoSeconds.QuadPart = grabCpuTicks.QuadPart - PreviousNanoSeconds.QuadPart;
    //reset tick count for next timing interval
    PreviousNanoSeconds.QuadPart = grabCpuTicks.QuadPart;
    //convert to nano seconds
    ElapsedNanoSeconds.QuadPart *= 1000000000;
    //Divide by CPU Cycles per second
    ElapsedNanoSeconds.QuadPart /= (cyclePerSecond.QuadPart);
    globalInterval = ElapsedNanoSeconds.QuadPart;
    //Global interval compensates for time computing so the timestep
    //is actually in whole correct including computation time and sleep time
    if(timeInterval > (globalInterval))
    {
        std::this_thread::sleep_for(std::chrono::nanoseconds(timeInterval - globalInterval));
    }

}

Windows Sleep函数的分辨率非常低。你需要一个高分辨率的计时器。通常的解决方案是使用多媒体计时器。

如果分辨率不够高,那么您将需要一个繁忙循环和性能计数器计时。