简单程序的高 CPU 使用率

High CPU usage of simple program

下面的代码是针对空 window 但在我的 Intel i3 上显示相对较高的 CPU 使用率 25%。我也试过 setFramerateLimit 没有任何变化。有没有办法减少 CPU 的使用?

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

问题是

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

是一个没有停顿的循环。由于像这样的 a 循环通常会消耗 100% 的 CPU 我不得不猜测你有一个 4 核 CPU 所以它消耗了一个完整的核,这是 CPU 容量的 25% =17=].

您可以在循环中添加一个暂停,这样就不会 运行 100% 的时间,或者您可以一起更改事件处理。

由于您没有在循环中调用 window.display(),因此请注意将线程暂停适当的时间,设置为 sf::RenderWindow::setVerticalSyncEnabledsf::RenderWindow::setMaxFramerateLimit

试试这个:

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

来自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.