[Prev] Table Of Contents [Next]

Using the Simple DirectMedia Layer API

Timers

  • Get the current time, in milliseconds

SDL_GetTicks() tells how many milliseconds have past since an arbitrary point in the past.

Tip:
In general, when implementing a game, it is better to move objects in the game based on time rather than on framerate. This produces consistent gameplay on both fast and slow systems.
Example:
#define TICK_INTERVAL    30

Uint32 TimeLeft(void)
{
    static Uint32 next_time = 0;
    Uint32 now;

    now = SDL_GetTicks();
    if ( next_time <= now ) {
        next_time = now+TICK_INTERVAL;
        return(0);
    }
    return(next_time-now);
}
  • Wait a specified number of milliseconds

SDL_Delay() allows you to wait for some number of milliseconds.

Since the operating systems supported by SDL are multi-tasking, there is no way to guarantee that your application will delay exactly the requested time. This should be used more as a way of idling for a while rather than to wake up at a particular time.

Tip:
Most operating systems have a scheduler timeslice of about 10 ms. You can use SDL_Delay(1) as a way of giving up CPU for the current timeslice, allowing other threads to run. This is important if you have a thread in a tight loop but want other threads (like audio) to keep running.
Example:
{
    while ( game_running ) {
        UpdateGameState();
        SDL_Delay(TimeLeft());
    }
}
 

[Prev] Table Of Contents [Next]