I am having trouble making my game's main loop to run at exactly N fps. Let's say i want game to run at constant 60 fps. Here is part of my code:

int ticksPerSecond = 60;
int skipTicks = 1000 / ticksPerSecond;
int maxFrameskip = 10;

// ...

    loops = 0;
    while (Environment.TickCount > nextGameTick && loops < maxFrameskip)
        nextGameTick += skipTicks;


As a result i am getting around 64 fps, not 60. Why is that and what am i doing wrong here?


You will have a rounding error.

(int)(1000 / 60) = 16 
1000 tickspersecond / 16 ticksperframe = 62.5 framespersecond 
// forgive my horrible units

Also, it looks like you abort your loop when you hit 10 updates. Is your update so fast that that ever happens?

  • \$\begingroup\$ Currently i am getting around 3000 fps without any limiting. \$\endgroup\$ – Skull Aug 19 '12 at 7:28
  • 2
    \$\begingroup\$ I don't think I know enough about the context of your question. I tried to give you the only answer I could. To me, it looks like your code draws as often as it can, and only limits its calls to update. That seems backwards if you are trying to fix your frames per second. Can you elaborate what your OnUpdate() and Render() functions do? \$\endgroup\$ – Seth Battin Aug 19 '12 at 16:56
  • \$\begingroup\$ OnUpdate function handles AI, input and other stuff, while Render draws everything on the screen. Nothing extraordinary. \$\endgroup\$ – Skull Aug 20 '12 at 3:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.