查询性能指标休眠问题
Query Performace Counter Sleeping Issue
你好,我正试图以一定的速度循环一段代码。在这个例子中,我的目标是每秒执行代码块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
函数的分辨率非常低。你需要一个高分辨率的计时器。通常的解决方案是使用多媒体计时器。
如果分辨率不够高,那么您将需要一个繁忙循环和性能计数器计时。
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 一个关于在C++中重载布尔运算符的问题
- 首要问题的答案让值班员搞错了
- setlocale的C++土耳其字符串问题
- 如何重构类层次结构以避免菱形问题
- 基于boost的程序的静态链接——zlib问题
- C++格式化输出问题
- 查询性能指标休眠问题