I'm trying to coerce GLFW 3.0 to stop nuking my CPU before moving forward with it as a framework to facilitate learning the API. I took the example from http://www.glfw.org/documentation.html and started searching around for means by which to limit it.
Presently, what I've gotten to work is this:
#include <iostream>
#include <chrono>
#include <thread>
#include <GLFW/glfw3.h>
int main(void)
{
typedef std::chrono::high_resolution_clock Clock;
typedef std::chrono::milliseconds milliseconds;
Clock::time_point currentTime, newTime;
milliseconds frameTime;
GLFWwindow* window;
if (!glfwInit())
return -1;
window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
if (!window)
{
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
while (!glfwWindowShouldClose(window))
{
currentTime = Clock::now();
glfwSwapBuffers(window);
glfwPollEvents();
newTime = Clock::now();
frameTime = std::chrono::duration_cast<milliseconds>(newTime - currentTime);
if(frameTime.count() < 16)
std::this_thread::sleep_for(milliseconds(16 - frameTime.count()));
std::cout << "Frame time: " << frameTime.count() << "ms" << std::endl;
}
glfwTerminate();
return 0;
}
Since GLFW already limits itself to 60fps, I thought that might work. And, indeed, it chops my CPU usage in half while the main loop runs. That might be good enough for now, but what I really want to know is:
How does one coax GLFW to wait for a signal and release the CPU instead of just roasting its tires on a while loop? I can't imagine it lacks that feature entirely.
Generally speaking, you don't. Usually, your program actually does stuff for that time. If you don't have stuff to do, then you yield some time to other processes. If no other processes are available to run, you just swallow it until you're ready to go.
Renderers generally try to render as fast as possible, because they will generally not be able to outrun the GPU. That's how most games work; they try to execute as fast as possible. They may have timers to do some yielding if the CPU is much faster than they expect, but more often than not, they just let the renderer run.
Also, expecting sleep_for to actually return in milliseconds(16 - frameTime.count()) time is not reasonable. It's only a minimum estimate, not a requirement.
It's better to use yield for that instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With