Cross Platform Time for dt

Generally a game loop will look something like this:

Generally the delta time slices between each game loop are useful to advance the game to the next frame, or tick. dt stands for the elapsed time since the last moment we asked for elapsed time, or, delta time. In effect we are using one frame’s worth of delayed time to advance state, so the visuals of the game are actually always one tick behind — but that’s totally acceptable and not noticeable to the user.

Getting that time slice is a little tricky. Usually games would want somewhat sub-millisecond resolution, since milliseconds is a pretty easy to reason about metric. 60 fps is about 16 milliseconds, so if we want to run a game at 60 fps we better use less than 16 milliseconds during each tick. If a major system of a game starts taking upwards of 5 or so milliseconds, then that system better be what the game is about! If a major system takes less than a millisecond, or roughly 1-2 milliseconds, it’s probably pretty well optimized. So we need sub-millisecond precision in our time function. Many time functions provided by operating systems are at best millisecond precision (not good enough if we want to measure less than a millisecond), or sometimes seconds precision.

Also, the time function itself should just be a straightforward function that returns a float, and has no parameters. So, I went through some digging and came up with a cross platform solution:

These functions should work on majority of major game platforms and give high resolution elapsed times between calls. They are intended to be used on the main thread within the main loop, once per tick.

If one wanted to use these functions for performance timing they should be modified to pass in some state, rather than rely on using static state. Static state is perfectly acceptable for the intended use case of main-loop main-thread. Be sure to read the comments in the source code!

I posted this source code in a finalized version here on github inside of tinytime.h.

 

TwitterRedditFacebookShare

Leave a Reply

Your email address will not be published. Required fields are marked *