Bastian Seeleib Bastian Seeleib -4 years ago 189
C Question

High CPU usage when GLFW / OpenGL Window isn't visible

I'm using GLFW so set up a Window with OpenGL. As i'm just started learning OpenGL and all the stuff around it, this might sound like a silly question, but why is the example program of GLFW using nearly 100% CPU when the Window is not actively displayed (minimized or hidden by another Window)?

Here is the GLFW exmaple, i'm running it on Mac OS with Xcode:

#include <GLFW/glfw3.h>
int main(void)
{
GLFWwindow* window;

if (!glfwInit()) /* Initialize the library */
return -1;

/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
if (!window)
{
glfwTerminate();
return -1;
}

/* Make the window's context current */
glfwMakeContextCurrent(window);

/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window))
{
/* Render here */

/* Swap front and back buffers */
glfwSwapBuffers(window);

/* Poll for and process events */
glfwPollEvents();
}

glfwTerminate();
return 0;
}

Answer Source

Your render loop is executed no matter what mimimization state of your window is.

If you want to stop rendering, you have to enhace the application logic a bit to track the state your window is in. GLFW supports user-defined a callback for such things with glfwSetWindowIconifyCallback() so your application can get noticed when the window is minimized or restored. You can the decide to stop the render loop, and can use glfwWaitEvents() to wait for something to happen (like the window being restored) without using all available CPU time.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download