简单程序的高CPU使用率

High CPU usage of simple program

本文关键字:CPU 使用率 程序 简单      更新时间:2023-10-16

下面的代码是针对一个空窗口的,但在我的英特尔i3上显示了25%的相对较高的CPU使用率。我也尝试了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;
    }
}

由于您没有在循环中调用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文档:

如果设置了限制,则窗口将在每次调用display()后使用一个小延迟,以确保当前帧持续足够长的时间以匹配帧速率限制。

问题是

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

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

您可以在循环中添加一个暂停,使其不是100%运行,也可以一起更改事件处理。