# Delta time not accurate enough

In my game i have a delta timer based almost exactly on the page from here

http://wiki.lwjgl.org/index.php?title=LWJGL_Basics_4_%28Timing%29

But if the the main loop is fast enough, my delta time variable is 0. This causes problems because it often happens several times in a row. I don't want to force a frame cap either. How can I remedy this?

EDIT: Setting a frame cap works, it only happens when the frame isn't capped. I've set delta to a minimum of 1, but that doesn't make it smooth. I could add a delay of one if it's zero, but that only fixes it for the next frame.

• You should perhaps explain why you don't want a frame cap, because it would be a solution to your problem. – Hackworth Dec 16 '14 at 15:16
• @Hackworth I feel like this is caused by something unrelated to the game rate. Even if I set a frame cap, players will be able to set it to what ever they want an in game option. – White Development Studios Dec 16 '14 at 15:25
• Then you need to clarify your question. At what frame rate do you get a delta of 0 (count the number of frames over a second with a global timer and record which frames gave a delta of 0), what else have you tried to fix the problem, have you actually tried setting a frame cap, why and where do you suspect another reason but limited timer accuracy? – Hackworth Dec 16 '14 at 15:36

Check out this blog entry on fixing your timestep. Essentially the advice here is to use a loop where you draw as much as you can until a fixed threshold of time has passed, then update.

Here is the recommended game loop;

double t = 0.0;
double dt = 0.01;

double currentTime = hires_time_in_seconds();
double accumulator = 0.0;

State previous;
State current;

while ( !quit )
{
double newTime = time();
double frameTime = newTime - currentTime;
if ( frameTime > 0.25 )
frameTime = 0.25;
currentTime = newTime;

accumulator += frameTime;

while ( accumulator >= dt )
{
previousState = currentState;
integrate( currentState, t, dt );
t += dt;
accumulator -= dt;
}

const double alpha = accumulator / dt;

State state = currentState * alpha +
previousState * ( 1.0 - alpha );

render( state );
}


From a high level point of view, what is happening is that the loop is interpolating between the last state and the current state and then drawing as much as it can. Each pass accumulates more elapsed time. When this accumulated time is over the 0.01 threshold the system does a full state update.

So if a frame takes less than 0.01s to draw, we can expect >1 frame to be drawn for each update.

If, however, the last frame lagged and accumulated more than twice the dt then it will do 2 updates or more before the next draw. So when the system lags it will drop frames before it drops updates.

So this loop will, in essence, update essentially every 0.01s, but will draw as much as is possible.