所以現在在我的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