【发布时间】:2015-09-19 16:08:09
【问题描述】:
我正在使用timeGetTime() 将帧速率限制为每秒 60 帧。我打算这样做的方法是获取渲染所述 60 帧所需的时间,然后使用 Sleep 等待第二秒的剩余时间。但由于某种原因,timeGetTime() 第一次调用它时返回的数字比我在渲染 60 帧后调用它时返回的数字要大。
代码如下:
标题
#ifndef __TesteMapa_h_
#define __TesteMapa_h_
#include "BaseApplication.h"
#include "Mundo.h"
class TesteMapa : public BaseApplication{
public:
TesteMapa()
virtual ~TesteMapa();
protected:
virtual void createScene();
virtual bool frameRenderingQueued(const Ogre::FrameEvent& evt);
virtual bool frameEnded(const Ogre::FrameEvent& evt);
virtual bool keyPressed(const OIS::KeyEvent &evt);
virtual bool keyReleased(const OIS::KeyEvent &evt);
private:
Mundo mundo = Mundo(3,3,3);
short altura, largura, passos, balanca, framesNoSegundo=0;
Ogre::SceneNode *noSol, *noSolFilho, *noCamera;
DWORD inicioSegundo = 0, finala;//inicioSegundo is the start variable and finala the ending variable
};
#endif
CPP相关功能
bool TesteMapa::frameEnded(const Ogre::FrameEvent& evt){
framesNoSegundo++;
if (inicioSegundo == 0)
inicioSegundo = timeGetTime();
else{
if (framesNoSegundo == 60){
finala = timeGetTime(); //getting this just to see the value being returned
Sleep(1000UL - (timeGetTime() - inicioSegundo));
inicioSegundo = 0;
framesNoSegundo = 0;
}
}
return true;
}
我在主函数中使用timeBeginPeriod(1) 和timeEndPeriod(1)。
【问题讨论】:
-
嗯,不,这绝不是操作系统中的错误。那个 Sleep() 调用很无聊。当 60 帧花费超过一秒的时间时,它将休眠很长时间。他们通常会这样做。
-
“60 帧”不是帧速率。我对你在问什么感到困惑。
-
您确定它会返回“更大的价值”吗?我的意思是,如果您的 60 帧花费超过 1000 毫秒,那么您最终将基本上永远处于休眠状态,因为您使用的是无符号类型。除了这是一种限制帧率的奇怪方式之外,我会使用
std::chrono::steady_clock而不是特定于 Windows 的函数。 -
@LightnessRacesinOrbit 我会编辑它。
-
首先,它是标准的一部分并且是跨平台的。其次,(我猜在你的情况下更重要的是)它具有表示时间和持续时间的特定类型(
std::chrono::time_point和std::chrono::duration,而不是通用DWORD),这可以最大限度地减少编写相关代码时可能犯的潜在错误时间测量。