Advertisement

C with SDL - Limit the frame rate

Started by May 09, 2018 07:54 PM
1 comment, last by frob 6 years, 6 months ago

Hello there! So, I want to ask you guys, is my solution for limiting the frame rate a good one? Of course, this is just a primitive version of it.

 


#include <SDL2/SDL.h>
#include <stdio.h>

int main(int argc, const char * argv[]) {
    SDL_Window *window;
    SDL_Renderer *renderer;
    
    SDL_Init(SDL_INIT_EVERYTHING);
    SDL_CreateWindowAndRenderer(640, 480, SDL_WINDOW_SHOWN | SDL_RENDERER_PRESENTVSYNC, &window, &renderer);
    
    Uint32 startTime = 0;
    Uint32 endTime = 0;
    Uint32 delta = 0;
    short fps = 60;
    short timePerFrame = 16; // miliseconds
    
    while (1) {
        if (!startTime) {
            // get the time in ms passed from the moment the program started
            startTime = SDL_GetTicks(); 
        } else {
            delta = endTime - startTime; // how many ms for a frame
        }
        
  
        // if less than 16ms, delay 
        if (delta < timePerFrame) {
            SDL_Delay(timePerFrame - delta);
        }
        
        // if delta is bigger than 16ms between frames, get the actual fps
        if (delta > timePerFrame) {
            fps = 1000 / delta;
        }
        
        printf("FPS is: %i \n", fps);
        
        startTime = endTime;
        endTime = SDL_GetTicks();
    }
    
    
    
    
    return 0;
}

 

When you eventually add your SDL_RenderPresent() call, that should throttle your speed.

You have the flag SDL_RENDERER_PRESENTVSYNC in your renderer, which means that whenever you switch rendering buffers with present, the function will block execution until the vsync has finished.

This will naturally limit your framerate to whatever the video card has, and it is the typical way to slow things down so your code is already on the right course. Thus if the user has a graphics card set at 60 Hz it will cap updates at 60 times per second, if they've got a 75 or 120 Hz monitor it can cap at 75 or 120 times per second.

This topic is closed to new replies.

Advertisement