Full CPU usage on Arch Linux

I have this code. (I have a folder called include that had glad.h in)

#include <iostream>
#include "include/glad.h"
#include <GLFW/glfw3.h>

int main() {
  glfwInit();

  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
  glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  glfwWindowHint(GLFW_REFRESH_RATE, 60);

  GLFWwindow* window = glfwCreateWindow(800, 800, "Project", NULL, NULL);

  if (window == NULL) {
    std::cout << "Failed to create the GLFW window!" << std::endl;
    glfwTerminate();
    return -1;
  }

  glfwMakeContextCurrent(window);

  glfwSwapInterval(0);

  while(!glfwWindowShouldClose(window)) {
    glfwPollEvents();
  }

  glfwDestroyWindow(window);

  glfwTerminate();

  return 0;
}

If I run it, it causes my CPU to run at 100%

I have tried glfwSwapInterval and glfwWindowHint(GLFW_REFRESH_RATE, 60); as shown in code but neither of them helped, my CPU still runs at 100%.

image

First of all you should have glfwSwapBuffers(window) inside your while loop. That’s where presenting back buffer will happen.

If you have set glfwSwapInterval to 0 that means do not synchronize with GPU vsync and run your code as much as you can - meaning it will use CPU 100%.

If you want synchronize with GPU vsync then you should have glfwSwapInterval(1); there instead. Then CPU usage should drop down a lot. Because no new frames will be summitted if GPU queue is full.

It’s also worth noting that the swap interval is sometimes ignored by drivers due to user settings (and sometimes bugs in drivers).

A technique you can use if you want to only update the visuals on changes in user input is to use glfwWaitEvents or glfwWaitEventsTimeout instead of glfwPollEvents.

However first implement @mmozeiko’s suggestions as these will likely achieve what you need.