Time Examples

Time based game loop

In a game loop you will want some kind of delay, to maintain a constant speed and to ensure your program doesn't always use 99% of the processor. This is a useful construct for maintaining a target framerate, rather than having a constant sleep time. Here the target interval is 30ms which equates to 1000/30 = 33 frames per second.

#define TICK_INTERVAL    30

static Uint32 next_time;

Uint32 time_left(void)
    Uint32 now;

    now = SDL_GetTicks();
    if(next_time <= now)
        return 0;
        return next_time - now;

/* main game loop */

    next_time = SDL_GetTicks() + TICK_INTERVAL;
    while ( game_running ) {
        next_time += TICK_INTERVAL;


On win32 it can be useful to call SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS) at the start of your program. This will push the resolution of SDL_Delay into the millisecond range. Normally, it has a resolution of about 10ms.

Time_Examples (last edited 2008-04-17 08:18:38 by localhost)