Skip to content
systemcoding.dev
GPU

Enable vsync with glfwSwapInterval

Enable vsync with glfwSwapInterval(1) so the buffer swap waits for the display refresh and the loop does not run flat out in GLFW 3.4.

1 min read
Summarize in AI

Without a swap interval, the loop renders as fast as the GPU allows and can tear. glfwSwapInterval(1) makes each swap wait for one vertical blank.

vsync.cc
glfwMakeContextCurrent(win);
glfwSwapInterval(1);

double last = glfwGetTime();
int frames = 0;
while (!glfwWindowShouldClose(win)) {
    draw();
    glfwSwapBuffers(win);
    glfwPollEvents();
    if (++frames == 60) {
        double now = glfwGetTime();
        printf("60 frames in %.2f s\n", now - last);
        last = now; frames = 0;
    }
}
Text
60 frames in 1.00 s

That output assumes a 60 Hz display; a 144 Hz monitor prints about 0.42 s. The call applies to the context current on the calling thread, so it must follow glfwMakeContextCurrent, as the GLFW context guide says. A value of 0 disables the wait, and drivers may override your choice from their control panel.

Some drivers support -1 for adaptive sync via WGL_EXT_swap_control_tear, but that is an extension, so check for it first.

Share

More snippets

GPU

List platforms with clGetPlatformIDs

Call clGetPlatformIDs twice, once for the count and once for the handles, then print each platform name with clGetPlatformInfo in OpenCL 3.0 C.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.