Search code examples
openglglfwvsync

Check that we need to sleep in glfwSwapBuffers method


I'm trying to create sample app using glew and glfw. The main loop is straightforward and looks like:

 while (running) {
    someUsefullMathHere();
    renderer->render(timeDelta);

    glfwSwapBuffers(window);
    glfwPollEvents();

    running = running & (!glfwWindowShouldClose(window));
}

The problem is that due to vsync current thread sleep for some tiin the glfwSwapBuffers execution (fps limited to 60 fps). I looking for a way to utilise this time for someUsefullMath method consecutive executions. Ideally code must looks something like:

while (running) {
    while (!timeToRenderAndSwap()) {
        someUsefullMathHere();
    }
    renderer->render(timeDelta);

    glfwSwapBuffers(window);
    glfwPollEvents();

    running = running & (!glfwWindowShouldClose(window));
}

Is there a way for this?


Solution

  • The only feasible way to do this is to utilize a thread for your someUsefulMathHere() function. You can use regular thread synchronization methods to read back any results (e.g. a mutex, to name just one of may possibilities), or to queue up new jobs. This way you'll not only gain spare CPU cycles while the main thread truly sleeps, but you can also get additional performance on a multi-core CPU.