Delta Time Calculation

Understanding Frame Time in Game Engines

What is Delta Time?

Delta Time (dt) is the amount of time that passed between the current frame and the previous frame.

In game development, delta time is used to make movement, animations, and physics independent from FPS (frames per second).

Without delta time, games run faster on high-end computers and slower on low-end computers.

Basic Formula

deltaTime = currentTime - previousTime

Example:

  • Previous frame: 1.000 seconds
  • Current frame: 1.016 seconds
  • Delta time: 0.016 seconds

0.016 seconds corresponds to approximately 60 FPS.

Using SDL Performance Counter

SDL provides a high precision timer using:

  • SDL_GetPerformanceCounter()
  • SDL_GetPerformanceFrequency()
Uint64 now = SDL_GetPerformanceCounter();
Uint64 frequency = SDL_GetPerformanceFrequency();

float dt = (float)(now - last_counter) / (float)frequency;

Complete Delta Time Function

float engine_calculate_delta_time(void) {
    static Uint64 last_counter = 0;
    static Uint64 frequency = 0;
    static float smooth_dt = 0.0f;

    const float MAX_DT = 0.25f;
    const float SMOOTH_ALPHA = 0.08f;

    if (frequency == 0)
        frequency = SDL_GetPerformanceFrequency();

    Uint64 now = SDL_GetPerformanceCounter();

    if (last_counter == 0) {
        last_counter = now;
        return 0.0f;
    }

    float dt = (float)(now - last_counter) / (float)frequency;
    last_counter = now;

    if (dt < 0.0f)
        dt = 0.0f;

    if (dt > MAX_DT)
        dt = MAX_DT;

    if (smooth_dt == 0.0f)
        smooth_dt = dt;
    else
        smooth_dt += SMOOTH_ALPHA * (dt - smooth_dt);

    return smooth_dt;
}

Delta Time Smoothing

smooth = smooth + α × (dt - smooth)

This is called an Exponential Moving Average.

It reduces jitter caused by unstable frame timings.

  • Small alpha = smoother movement
  • Large alpha = more responsive

Frame Independent Movement

Delta time is commonly used like this:

position += velocity * delta_time;

Example:

  • Velocity = 100 pixels/sec
  • Delta Time = 0.016

Result:

position += 100 * 0.016;
position += 1.6f;

The object moves consistently regardless of FPS.

Why Clamp Delta Time?

Sometimes the game freezes temporarily because:

  • Window dragging
  • Debugger pause
  • Alt-tab
  • Loading spikes

Without clamping, physics and movement can explode due to a massive delta time value.

This is commonly known as:

"Spiral of Death"

Fixed Timestep vs Variable Timestep

Variable Timestep

update(delta_time);

Easier to implement, commonly used for rendering.


Fixed Timestep

while (accumulator >= FIXED_DT) {
    physics_update(FIXED_DT);
    accumulator -= FIXED_DT;
}

More stable for physics and deterministic gameplay.