I am currently working on a platformer and am trying to implement timestep, but for frame rate limits of more than 60, the processor load increases from 1% to 25% or more.
I made this minimal program to demonstrate this problem. In the code that describes the problem and what I tested, there are two comments (lines 10-13, lines 26-30).
Please note that the FPS stuff is not relevant to the problem (I think).
I tried to keep the code short and simple:
#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; }
I do not want to use SFML setFramerateLimit (), but my own implementation is with sleep, because I will use fps data to update my physics, etc.
Is there a logical error in my code? I do not see this, since it works with a frame rate limitation of, for example, 60 (or less). Is it because I have a 60 Hz monitor?
PS: Using SFML window-> setVerticalSync () does not change the results