A. *_* D. 6 c++ cpu frame-rate cpu-usage sfml
我目前正在开发平台并尝试实现时间步长,但对于超过60的帧速率限制,CPU使用率从1%上升到25%甚至更高.
我制作了这个最小程序来演示这个问题.代码中有两条注释(第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;
}
Run Code Online (Sandbox Code Playgroud)
我不想使用SFML的setFramerateLimit(),而是我自己的睡眠实现,因为我将使用fps数据来更新我的物理和东西.
我的代码中是否存在逻辑错误?我没有看到它,因为它的帧速率限制为例如60(或更低).是因为我有60赫兹的显示器吗?
PS:使用SFML的窗口 - > setVerticalSync()不会改变结果
问题是,它并没有完全帮助你使用CPU,但我尝试了你的代码,它在120 FPS(以及更多)的1%CPU使用率下工作正常.当您使用"游戏循环"制作游戏或交互式媒体时,您不希望通过睡眠而失去性能,您希望使用计算机可以提供的尽可能多的CPU时间.您可以处理其他数据,例如加载内容,寻路算法等,或者不对渲染设置限制,而不是休眠.
我提供了一些有用的链接和代码,这里是:
类似的问题:没有帧率限制的运动C++ SFML.
你真正需要的是固定的时间步骤.看一下SFML Game开发书籍源代码.以下是来自以下内容的有趣片段
Application.cpp:Run Code Online (Sandbox Code Playgroud)const sf::Time Game::TimePerFrame = sf::seconds(1.f/60.f); // ... sf::Clock clock; sf::Time timeSinceLastUpdate = sf::Time::Zero; while (mWindow.isOpen()) { sf::Time elapsedTime = clock.restart(); timeSinceLastUpdate += elapsedTime; while (timeSinceLastUpdate > TimePerFrame) { timeSinceLastUpdate -= TimePerFrame; processEvents(); update(TimePerFrame); } updateStatistics(elapsedTime); render(); }如果这不是你想要的,请参阅" 修复你的时间步骤! ",Laurent Gomila本人在SFML论坛中将其链接起来.