# How to calculate delta time with SDL?

I have heard that you can calculate delta time with two functions called SDL_GetPerformanceCounter and SDL_GetPerformanceFrequency. I'm not sure how they work completely, but I heard it is a bit similar to using SDL_GetTicks()

    Uint64 NOW, LAST;
double deltaTime = 0;

while (somebool)
{
LAST = SDL_GetPerformanceCounter();
NOW = SDL_GetPerformanceCounter();
LAST = NOW;

deltaTime = (NOW - LAST) / (double)SDL_GetPerformanceFrequency();

/**Rendering**/
}


I have this code but whenever I print out deltaTime or try to use it it always equals some really random and insane numbers. Is this correct?

• the code shown would always set delta time to 0, right? (NOW=LAST, NOW - LAST.) – david van brink Nov 4 '15 at 18:56

When reading the code-example provided by SDL on the SDL_GetPerformanceFrequency I could easily find out how you could calculate a deltatime using these functions.

It should basically come down to this for you:

Uint64 NOW = SDL_GetPerformanceCounter();
Uint64 LAST = 0;
double deltaTime = 0;

while (somebool)
{
LAST = NOW;
NOW = SDL_GetPerformanceCounter();

deltaTime = (double)((NOW - LAST)*1000 / (double)SDL_GetPerformanceFrequency() );

/**Rendering**/
}


Note: the first frame will always have a deltatime of 0 or something very close to it

This should fill the value deltaTime in milliseconds, this can easily be converted to seconds by multiplying the final result with 0.001.

• This would be more accurate: deltaTime = ((NOW - LAST)*1000 / (double)SDL_GetPerformanceFrequency() ); since this avoid clamping the number due to the integer division. – Mortennobel Sep 20 '16 at 15:30

They way I've gone about calculating the delta time has been via SDL_GetTicks():

struct Clock
{
uint32_t last_tick_time = 0;
uint32_t delta = 0;

void tick()
{
uint32_t tick_time = SDL_GetTicks();
delta = tick_time - last_tick_time;
last_tick_time = tick_time;
}
};


Then I simply tick a Clock instance in the main loop.

• While this approach works too, the other answer is more precise. – Tyyppi_77 Jun 15 '16 at 14:53