所以现在在我的OpenGL游戏引擎中,当我的渲染线程几乎没有任何关系时,它占用了我的CPU可以给它的最大值。 Windows任务管理器显示我的应用程序占用了25%的处理量(我有4个硬件线程,因此25%是一个线程可以使用的最大值)。当我根本没有启动渲染线程时,我得到0-2%(这是它自己的担心,因为它所做的全部都是运行SDL输入循环)。为什么我的渲染线程占用100%cpu?
那么,我的渲染线程究竟做了什么?这里有一些代码:
Timer timer;
while (gVar.running)
{
timer.frequencyCap(60.0);
beginFrame();
drawFrame();
endFrame();
}
让我们来看看其中的每一个。 Timer
是我使用SDL_GetPerformanceCounter
制作的定制计时器类。 timer.frequencyCap(60.0);
旨在确保循环每秒不会运行超过60次。下面的代码为Timer::frequencyCap()
:
double Timer::frequencyCap(double maxFrequency)
{
double duration;
update();
duration = _deltaTime;
if (duration < (1.0/maxFrequency))
{
double dur = ((1.0/maxFrequency) - duration) * 1000000.0;
this_thread::sleep_for(chrono::microseconds((int64)dur));
update();
}
return duration;
}
void Timer::update(void)
{
if (_freq == 0)
return;
_prevTicks = _currentTicks;
_currentTicks = SDL_GetPerformanceCounter();
// Some sanity checking here. //
// The only way _currentTicks can be less than _prevTicks is if we've wrapped around to 0. //
// So, we need some other way of calculating the difference.
if (_currentTicks < _prevTicks)
{
// If we take difference between UINT64_MAX and _prevTicks, then add that to _currentTicks, we get the proper difference between _currentTicks and _prevTicks. //
uint64 dif = UINT64_MAX - _prevTicks;
// The +1 here prvents an off-by-1 error. In truth, the error would be pretty much indistinguishable, but we might as well be correct. //
_deltaTime = (double)(_currentTicks + dif + 1)/(double)_freq;
}
else
_deltaTime = (double)(_currentTicks - _prevTicks)/(double)_freq;
}
接下来的3个功能是相当简单的(在此阶段):
void Renderer::beginFrame()
{
// Perform a resize if we need to. //
if (_needResize)
{
gWindow.getDrawableSize(&_width, &_height);
glViewport(0, 0, _width, _height);
_needResize = false;
}
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
}
void Renderer::endFrame()
{
gWindow.swapBuffers();
}
void Renderer::drawFrame()
{
}
渲染线程使用的std ::线程创建。我能想到的唯一解释是timer.frequencyCap
以某种方式不起作用,除非我在主线程中使用完全相同的功能,并且我在0-2%空闲。
我在这里做错了什么?
添加日志记录,直到您明白发生了什么。 – 2014-09-25 06:05:09
强烈建议您废除自己的计时器控制并使用图形驱动程序提供的[交换间隔控制](http://www.opengl.org/wiki/Swap_Interval)。 – starrify 2014-09-25 06:23:31
任何sleep_for调用保证低于100%的CPU负载。检查这个条件if(duration <(1.0/maxFrequency))' – 9dan 2014-09-25 06:30:29