Reputation: 1626
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;
}
}
Upvotes: 3
Views: 1413
Reputation: 19607
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.
Upvotes: 7
Reputation: 180585
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.
Upvotes: 3