Framerate Cap in SDL
Continuing to learn SDL, I thought it might be good to apply framerate cap to 60 rather than letting my GPU push 8000 to 9000 FPS...
Now it needs just a bit of math which I implemented inside the main loop.
Now framerate is just how many frames we see in 1 second, and the more the frames that means the frametime is smaller. Frametime is just the time a frame stays on the screen.
To achieve 60 FPS we needed to make each frame stay for 16.6ms on the screen. Therefore the logic being we calculate the time of a frame's start to the end of its whole rendering. Then we check that if the rendering is done in less than 16.6ms, if yes, we wait for the remaining time.
Its something like this:
Time_Start = 0ms (Frame Render Start)
...Frame Does Rendering...
Time_End = 5ms (Frame Render End)
Total time for frame to render = (Time_End - Time_Start) = 5ms
Since 5ms is less than 16.6ms we wait for the remaining time
therefore,
waitTime = (16.6ms - 5ms)
Once the wait time is over we re-render and do the same thing all over again. If incase the worktime is greater than 16.6ms (60 FPS) we don't wait and render the next frame immediately.
To get the time we use the SDL_GetTicks() function that returns the time since SDL_INIT.
So to implement it in C++,
#define FRAMERATE_CAP 60
float const target_frametime = 1000/FRAMERATE_CAP; //Gives around 16.6ms
...lines of code...
//our main loop
bool windowIsRunning = true;
while(windowIsRunning){
//get the time of the framestart
Uint32 framestart = SDL_GetTicks();
...other lines of code...
//get the time of how long it took to render a frame (currentTime - frameStart)
Uint32 actual_frametime = SDL_GetTicks() - framestart;
//When done we check if the application took less than our designated time (16.6ms) if yes we wait for the rest of the time
if(actual_frametime <= target_frametime){
SDL_Delay(target_frametime - actual_frametime);
}
}
The logic is simple - We get the time from SDL_INIT for that frame and then again get it after the frame is done rendering and to get the total time it took for the frame to render we just substract the time after frame end to that of the framestart.
Then we just check that the time needed to render the current frame was lower than that of the target frametime, if yes then we wait out the remaining time using SDL_Delay() function.
Click here for Source Code.