18
\$\begingroup\$

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?

\$\endgroup\$
1
  • 2
    \$\begingroup\$ the code shown would always set delta time to 0, right? (NOW=LAST, NOW - LAST.) \$\endgroup\$ Commented Nov 4, 2015 at 18:56

2 Answers 2

21
\$\begingroup\$

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.

Reference: https://wiki.libsdl.org/SDL_GetPerformanceFrequency

\$\endgroup\$
1
  • 8
    \$\begingroup\$ This would be more accurate: deltaTime = ((NOW - LAST)*1000 / (double)SDL_GetPerformanceFrequency() ); since this avoid clamping the number due to the integer division. \$\endgroup\$ Commented Sep 20, 2016 at 15:30
5
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ While this approach works too, the other answer is more precise. \$\endgroup\$
    – user35344
    Commented Jun 15, 2016 at 14:53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .