简体   繁体   中英

High CPU usage of simple program

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;
    }
}

Since you're not calling 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.

The issue is

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

Is a loop with no pause in it. Since an a loop like this normally consumes 100% of the CPU I would have to guess that you have a 4 core CPU so it is consuming one entire core which is 25% of the capacity of the CPU.

You could add a pause in the loop so it is not running 100% of the time or you could change the event handling all together.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM