为什么当我运行这个简单的代码而什么也不做,这个应用程序的CPU使用率大约是0.4%
#include <SFML/Graphics.hpp>
int main()
{
sf::RenderWindow window(sf::VideoMode(800, 800), "hi", sf::Style::Close | sf::Style::Titlebar);
window.setFramerateLimit(60);
sf::Event event;
bool lostFocus = false;
while (window.isOpen())
{
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
else if (event.type == sf::Event::LostFocus)
lostFocus = true;
else if (event.type == sf::Event::GainedFocus)
lostFocus = false;
}
if (!lostFocus)
{
window.clear(sf::Color::White);
window.display();
}
}
}但是当我点击其他应用程序时,这个应用程序的CPU使用率增加到12%。
GainedFocus真的消耗了这么多的cpu资源吗?
(我只是想简单地暂停一下游戏,看看这个cpu的使用)
发布于 2022-09-28 16:26:49
如前所述,当您的窗口没有焦点,并且您没有更新窗口时,循环进入一个热旋,在那里它不断地检查事件。当您失去焦点时,您反而希望阻止并等待GainedFocus事件的发生。作为一个非常简单的例子,您可以这样做
void block_until_gained_focus(sf::Window& window) {
sf::Event event;
while (true) {
if (window.waitEvent(event) && event.type == sf::Event::GainedFocus) {
return;
}
}
}那么您的主游戏循环可能看起来就像
while (window.isOpen())
{
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
else if (event.type == sf::Event::LostFocus)
wait_until_gained_focus(window);
}
window.clear(sf::Color::White);
window.display();
}现在,如果您想在失去焦点的情况下进行额外的工作,您将需要一个不同的实现,但是这里的关键是使用waitEvent而不是pollEvent。
https://stackoverflow.com/questions/73884580
复制相似问题