【发布时间】:2014-04-03 10:40:55
【问题描述】:
我目前正在开发一个平台游戏并尝试实现一个时间步长,但是对于大于 60 的帧速率限制,CPU 使用率会从 1% 上升到 25% 甚至更多。
我制作了这个最小的程序来演示这个问题。代码中有两个 cmets(第 10-13 行、第 26-30 行)描述了问题和我测试过的内容。
请注意,FPS 的内容与问题无关(我认为)。
我尽量保持代码简短:
#include <memory>
#include <sstream>
#include <iomanip>
#include <SFML\Graphics.hpp>
int main() {
// Window
std::shared_ptr<sf::RenderWindow> window;
window = std::make_shared<sf::RenderWindow>(sf::VideoMode(640, 480, 32), "Test", sf::Style::Close);
/*
When I use the setFramerateLimit() function below, the CPU usage is only 1% instead of 25%+
(And only if I set the limit to 60 or less. For example 120 increases CPU usage to 25%+ again.)
*/
//window->setFramerateLimit(60);
// FPS text
sf::Font font;
font.loadFromFile("font.ttf");
sf::Text fpsText("", font, 30);
fpsText.setColor(sf::Color(0, 0, 0));
// FPS
float fps;
sf::Clock fpsTimer;
sf::Time fpsElapsedTime;
/*
When I set framerateLimit to 60 (or anything less than 60)
instead of 120, CPU usage goes down to 1%.
When the limit is greater, in this case 120, CPU usage is 25%+
*/
unsigned int framerateLimit = 120;
sf::Time fpsStep = sf::milliseconds(1000 / framerateLimit);
sf::Time fpsSleep;
fpsTimer.restart();
while (window->isOpen()) {
// Update timer
fpsElapsedTime = fpsTimer.restart();
fps = 1000.0f / fpsElapsedTime.asMilliseconds();
// Update FPS text
std::stringstream ss;
ss << "FPS: " << std::fixed << std::setprecision(0) << fps;
fpsText.setString(ss.str());
// Get events
sf::Event evt;
while (window->pollEvent(evt)) {
switch (evt.type) {
case sf::Event::Closed:
window->close();
break;
default:
break;
}
}
// Draw
window->clear(sf::Color(255, 255, 255));
window->draw(fpsText);
window->display();
// Sleep
fpsSleep = fpsStep - fpsTimer.getElapsedTime();
if (fpsSleep.asMilliseconds() > 0) {
sf::sleep(fpsSleep);
}
}
return 0;
}
我不想使用 SFML 的 setFramerateLimit(),而是我自己的 sleep 实现,因为我将使用 fps 数据来更新我的物理和东西。
我的代码中是否存在逻辑错误?我看不到它,因为它的帧速率限制为例如 60(或更少)。是因为我有一个 60 Hz 的显示器吗?
PS:使用 SFML 的 window->setVerticalSync() 不会改变结果
【问题讨论】:
标签: c++ cpu cpu-usage sfml frame-rate