Understanding GameTime

Understanding GameTime

  • Comments 21

Time can be a surprisingly slippery concept to get to grips with. Back when I was working on Allegro it caused the most common question from new programmers, and even though XNA does more than Allegro to handle time for you, it appears some people are still confused. Hopefully this post will clarify how time works in the XNA Framework.

 

Game.IsFixedTimeStep = true

By default XNA runs in fixed timestep mode, with a TargetElapsedTime of 60 frames per second. This provides a simple guarantee:

  • We will call your Update method exactly 60 times per second
  • We will call your Draw method whenever we feel like it

Digging into exactly what that means, you will realize there are several possible scenarios depending on how long your Update and Draw methods take to execute.

The simplest situation is that the total time you spend in Update + Draw is exactly 1/60 of a second. In this case we will call Update, then call Draw, then look at the clock and notice it is time for another Update, then Draw, and so on. Simple!

What if your Update + Draw takes less than 1/60 of a second? Also simple. Here we call Update, then call Draw, then look at the clock, notice we have some time left over, so wait around twiddling our thumbs until it is time to call Update again.

What if Update + Draw takes longer than 1/60 of a second? This is where things get complicated. There are many reasons why this could happen:

  1. The computer might be slightly too slow to run the game at the desired speed.
  2. Or the computer might be way too slow to run the game at the desired speed!
  3. The computer might be basically fast enough, but this particular frame might have taken an unusually long time for some reason. Perhaps there were too many explosions on screen, or the game had to load a new texture, or there was a garbage collection.
  4. You could have paused the program in the debugger.

We do the same thing in response to all four causes of slowness:

  • Set GameTime.IsRunningSlowly to true.
  • Call Update extra times (without calling Draw) until we catch up.
  • If things are getting ridiculous and we are too far behind, we just give up.

If you think about how this algorithm deals with the four possible causes of slowdown I listed above, you'll see it handles them all rather well:

  1. Even if the computer is too slow to run Update + Draw inside a single frame, chances are that Update + Update + Draw will fit into two frames. The game may look a little jerky, but it will still play correctly. If the programmer is particularly smart they might even notice that we set IsRunningSlowly, and automatically reduce detail or turn off special effects to speed things up.
  2. If the computer is way too slow (ie. if the Update method alone is too slow to fit into a single frame) there isn't really much we can do, other than set IsRunningSlowly, cross our fingers, and hope the game might do something clever in response to that. Most of the time, though, if you find yourself in this situation you just need a faster computer!
  3. If a particular frame happens to take unusually long, we automatically call Update some extra times to catch up, after which everything carries on as normal. The player may notice a slight glitch, but we automatically correct for this to minimize the impact.
  4. Pausing in the debugger will leave the game a long way behind where the clock says it should be, so our algorithm will give up, accept that it has lost some time, and continue running smoothly from the time execution was resumed.

In summary, you don't need to do anything special to take advantage of our our fixed timestep logic. Just make sure you put all your game logic inside the Update method (not in Draw!) and everything will run at a nice constant speed.

For bonus points you can automatically adjust your game detail in response to the IsRunningSlowly flag, but most games are fine not bothering with this.

If you put breakpoints on your Update and Draw methods you may notice us calling Update more often than Draw, but this is just because the breakpoint has made us late and we are trying to catch up. Timing is a great example of the Heisenberg Uncertainty Principle: by examining the way the timing system is behaving, you change the timings, and get different results than when you let the game run normally.

You can change the TargetElapsedTime property if you want to run a fixed timestep game at something other than 60 frames per second. We chose that default because it matches the standard television refresh rate, but some games might want to slow this down to 30 frames per second.

 

Game.IsFixedTimeStep = false

If you disable fixed timesteps, XNA does nothing clever for you. Our algorithm in this mode is extremely simple:

  • Update
  • Draw
  • Rinse, lather, repeat

(that is actually a slight simplification, but the details are unimportant)

There are some significant advantages to running in this mode:

  • Because the game is not tied to any fixed update frequency, it can do a better job of exactly matching your monitor refresh rate. This is important for twitch FPS games that want to render at exactly 70, 90, 120, or however else the user has configured their monitor.
  • This mode can be more efficient when running on slow computers. Instead of having to call Update several times to catch up, we can just call it once with a large ElapsedTime value. If the game is programmed well, it may be able to handle that more efficiently than if Update was called several times with a smaller ElapsedTime.

The downside is that variable timestep games are much harder to program. Even simple computations such as "add velocity to position" must be adapted to take the elapsed time into account. For anything more than the most trivial calculations this requires you to integrate the equation, so you can evaluate how it changes over a period of time. Some people are good at calculus, but I'm not, and I don't much enjoy having to deal with such things every time I want to move a game object!

 

Holy Wars

So, which mode is better? Game programmers have argued about this since the dawn of time, and will probably still be arguing when the universe implodes around us.

As a rule of thumb, console programmers prefer fixed timesteps, while PC programmers usually go for variable timing mode. There are two main reasons for this disparity:

  • Consoles are usually connected to a 60 hz television, while PC monitors can be set to many different refresh rates.
  • The speed of a console is known ahead of time, so while games must handle single frames that take longer than expected, it is unlikely they will be consistently too slow for the machine they are running on. PC games must support a wider range of hardware, so it is more important for them to cope well with way-too-slow machines.

But there are no absolute rules. I've seen console games that worked well using variable timesteps, and I personally shipped a PC title that ran just fine with a 60 fps fixed timestep.

XNA defaults to fixed timestep mode because that is easier to program, but you are welcome to change this if you disagree with our choice.

 

Multiple Update Frequencies

There is no law saying all parts of a game must update at the same frequency. For instance MotoGP combined three different update rates:

  • The main game logic ran at a fixed timestep 60 fps. This included input, sound, user interface logic, camera movement, rider animations, AI, and graphical effects.
  • The physics update ran at a fixed timestep 120 fps (we just called it twice in a row from our main Update method). This provided a more accurate simulation, which was important for simulating vehicles moving at extremely high speeds and right on the edge of loosing traction.
  • The network update ran at a fixed timestep anywhere between 4 and 30 fps, depending on how many players were in the game. The more players there were, the more data we had to send, so we adjusted by sending it less often to conserve bandwidth.

Running some parts of your update logic less often than others is a great way to make games more efficient. For instance pathfinding and AI often only need to be updated a couple of times a second. Once you have found a good path or made the decision to attack, you can follow that decision without having to repeat the entire original calculation on each update.

  • I saw that there was an "IsRunningSlowly" property, but could never really figure out its use. Now I know!

    Also, on MotoGP, how would running the physics system twice work? Did you update positions/speeds and then do the same again just so that the deltas were smaller? Was it something like what follows?

    physSim.Update();

    physSim.Update();

    I'm curious to see how something like that would work... Nice post, btw, thanks.

  • The default 60Hz-because-of-TV-refresh makes me wonder: does this change to 50Hz when the XBox is connected to a PAL TV? Or - from a not too serious POV - is this just another default chosen in the spirit of "We are Americans and deal with i18n issues in v.Next"? :]

  • Shawn.. You're awesome..

    Thanks for your article.

    This is exactly what I am looking in the past few days. This is by far the best and most comprehensive I can find regarding game timing.. :)

  • Hmmm... In our DBP entry we opted for a fixed timestep at some 33 updates per second to keep CPU load low *and* enabled VSyncing to prevent tearing. Fraps indicated a steady 75 FPS, while examining the gameTime.ElapsedTime in the Update method shows it is called at the fixed timestep (33 FPS). So it would seem Draw can be called more often than Update.

    I don't know if I'm misreading your post, but the scenarios you described only seem to mention "x calls to Update + one call to Draw()" (i.e. Draw is always limited by Update frequency), so I thought I'd point this out.

    Please drop a line if this is horrible abuse of the fixed timestep :)

  • > I don't know if I'm misreading your post, but > the scenarios you described only seem to

    > mention "x calls to Update + one call to Draw

    > ()" (i.e. Draw is always limited by Update

    > frequency), so I thought I'd point this out.

    At the moment we sometimes call draw more often than we really should (there's not really any point calling it twice if we didn't do an update in between, since it will just be drawing the same thing again!). This is likely to change in future versions.

  • Björn comments on my previous post : The default 60Hz-because-of-TV-refresh makes me wonder: does this

  • Shawn says...

    > If a particular frame happens to take unusually

    > long, we automatically call Update some extra

    > times to catch up, after which everything carries

    > on as normal. The player may notice a slight

    > glitch, but we automatically correct for this

    > to minimize the impact.

    Does this mean you keep a list of the last x frame times and pass us the average?

    Currently I'm setting Game.IsFixedTimeStep = false and handling the fixed physics myself.  I have to do some interpolation between last state and current state in Draw to get smooth animation.  It all works but I'm not sure if it's overkill.  It does isolate me from monitor frequencies, syncing to refresh, etc though.

  • > At the moment we sometimes call draw more

    > often than we really should (there's not

    > really any point calling it twice if we

    > didn't do an update in between, since it will

    > just be drawing the same thing again!). This

    > is likely to change in future versions.

    Well, there actually is, if you consider VSyncing to prevent tearing a good reason. I always thought this was an exaggerated problem, but VSync does seem to make a difference in quality on my crappy Dell monitor.

    Regardless, in my not-so-humble opinion I don't think it would be a good idea to change this behavior. As the need for your post indicates, the time handling is complicated enough as is. If the actual drawing frequency would be limited by the update interval, this might lead to more confusion (VSync already spawned countless topics of "I can't get my FPS above 60") and it would effectively render DX VSync useless in most fixed timestep scenarios.

    Not drawing if nothing changed might be the smart thing to do, but it should make little difference as long as you can maintain your target rendering framerate anyway. If I can afford to draw at 75 FPS, why would I want to be limited by a fixed timestep that I typically only want to apply to the simulation/update?

    Just my 2 cents though :)

  • > Not drawing if nothing changed might be the

    > smart thing to do, but it should make little

    > difference as long as you can maintain your

    > target rendering framerate anyway. If I can

    > afford to draw at 75 FPS, why would I want to

    > be limited by a fixed timestep that I typically

    > only want to apply to the simulation/update?

    Little difference, yes (the implementation in the framework today works fine in practice) but even a little difference is still a difference, and if it is possible to make even a little improvement, surely that's worth doing? :-)

    Think of it this way: if an Update + Draw cycle completes within the alloted timespan, you have the choice of calling Draw again, or waiting doing nothing for the timespan to expire. What difference does this choice make to anything?

    On the surface, nothing. Calling Draw twice without an Update in between should (if the game is programmed correctly) render exactly the same thing again, so the user will see no visible difference at all (the only time this could render something different is if the game was doing some kind of clever interpolation in their Draw method, but in that case they really ought to be using variable timestep mode in the first place).

    There are in fact exactly two ways in which calling Draw again can make a difference:

    1: This may affect the figures reported by framerate measuring programs. I think this is kind of a bogus argument, though, because giving yourself a fake FPS boost by calling Draw without Update is really cheating! If people are trying to measure their game performance using these FPS counters, they have other problems because FPS isn't really a suitable way to measure such things in the first place (that's a whole other topic :-)

    2: Waiting is interruptible, but Draw is not. This is the biggie. Consider a game that runs just over 60 fps. Update + Draw completes, and there are a few milliseconds left over, so we call Draw again. Now the timespan expires, but the game is in the middle of Draw, so we have to wait for Draw to complete before we can go back to Update. This could put us significantly behind where we want to be (although always less than an entire frame). The error will be corrected over the next couple of frames as we call Update + Draw in sequence, using the leftover time to make up for what we lost by the extra Draw. There is no actual dropped frame here (we never have to call Update twice in a row without a Draw) but there is a lack of smoothness in our Update calls: we have a biggish gap between two of them, followed by a sequence closer together, then another biggish gap, etc. This is why it would be better to just wait: that way Update can be called at exactly the right time, and will always be perfectly evenly spaced.

    Does this actually make a noticeable difference? Probably not. But I'm a perfectionist.

  • Awesome work as usual Shawn :)

  • Some good points covered here Shawn. Keep 'em coming, good stuff.

  • "Running some parts of your update logic less often than others is a great way to make games more efficient. For instance pathfinding and AI often only need to be updated a couple of times a second. Once you have found a good path or made the decision to attack, you can follow that decision without having to repeat the entire original calculation on each update."

    Great advice.

  • It would be great if you write also about proper performance counters like FPS counter, frame time counter etc... in the context of the above text.

    Thank you!

  • Allow me to respond :)

    > 1: This may affect the figures reported by

    > framerate measuring programs. I think this is

    > kind of a bogus argument, though, because

    > giving yourself a fake FPS boost by calling

    > Draw without Update is really cheating!

    I beg to differ. This may hold true if you knowingly rig your update scheme to do this, but who in their right minds is going to cheat themselves to get a fictive performance boost? The main reasons I like this behavior is:

    1. It's predictable

    2. It helps budget your draw performance

    During development we disable VSync so the drawing runs at max speed and we can get a better idea of how the performance of the rendering code is holding up. By chaining the drawing together with the updating, it seems to me it gets harder to get a straightforward idea of the performance. Yes, yes, you might argue we should profile (and not use the hyperbolically distrubted framerate anyway), but I think a profiler is no excuse for introducing needlessly complex behavior.

    > 2: Waiting is interruptible, but Draw is not.

    > This is the biggie. Consider a game that runs

    > just over 60 fps. Update + Draw completes,

    > and there are a few milliseconds left over,

    > so we call Draw again. Now the timespan

    > expires, but the game is in the middle of

    > Draw, so we have to wait for Draw to complete

    > before we can go back to Update. This could

    > put us significantly behind

    True, but isn't this already an unfortunate side-effect of the current smart update/draw scheme? I appreciate the efforts put into XNA to keep the game running smoothly, but at some point you'll have to draw the line and give up on trying to fix unperformant code. It might be a better idea to confront XNA coders straight up when their performance is going down the drain instead of keeping them in the dark with smart tricks until they hit a wall.

    > Does this actually make a noticeable

    > difference? Probably not. But I'm a

    > perfectionist.

    Commendable, but why sacrifice transparency and predictability for the sake of unnoticable perfection? :)

  • Hello Shawn,

    I'm experiencing some rendering "lags" with my xna game. I tried to reproduce it with the simpliest game application. I achieved to get the same lag feeling after the application get frozen for a little time (by moving the game window for example).

    I wrote a thread about this on the xna forum. Could I have your point of view ?

    http://forums.xna.com/forums/p/45105/270038.aspx#270038

    Thanks.

Page 1 of 2 (21 items) 12
Leave a Comment
  • Please add 4 and 8 and type the answer here:
  • Post