rowman rowman - 3 months ago 30
C++ Question

SFML/C++ - High CPU usage

The code below is for an empty window but shows relatively high CPU usage of 25% on my Intel i3. I also tried the

setFramerateLimit
with no change. Is there a way to reduce the CPU usage?

#include<SFML/Window.hpp>

void processEvents(sf::Window& window);

int main()
{
sf::Window window(sf::VideoMode(800, 600), "My Window", sf::Style::Close);
window.setVerticalSyncEnabled(true);

while (window.isOpen())
{
processEvents(window);
}
return 0;
}

void processEvents(sf::Window& window)
{
sf::Event event;
window.pollEvent(event);
switch (event.type)
{
case sf::Event::Closed:
window.close();
break;
}
}

Answer

Since you're not doing window.display() in the loop, there's noting to halt the thread for the appropriate amount of time, set with sf::RenderWindow::setVerticalSyncEnabled or sf::RenderWindow::setMaxFramerateLimit.

Try this:

while (window.isOpen())
{
    processEvents(window);

    // this makes the thread sleep
    // (for ~16.7ms minus the time already spent since
    // the previous window.display() if synced with 60FPS)
    window.display();
}

From SFML Docs:

If a limit is set, the window will use a small delay after each call to display() to ensure that the current frame lasted long enough to match the framerate limit.