Frame Capping With Really Bad Timers

The following piece of code is written in Java, but it should be easy to port it to other languages.

long lastFrame=0;
float yield=10000f;
float frameAverage=16f; //start with desired msec per frame

[...]

long timeNow = System.currentTimeMillis();
//rolling average for the last 10 time inputs
frameAverage = (frameAverage * 10 + (timeNow - lastFrame)) / 11;
lastFrame=timeNow;

//16f = for 16msec
//0.1f = damping value
//+0.05f ensures that it can grow faster after it ran flat out for a while
yield+=yield*((16f/frameAverage)-1)*0.1f+0.05f;

for(int i=0;i<yield;i++)
    Thread.yield();

It uses rolling average and proportional adjusting yield (with some damping).

It relies on a sorta steady CPU load with small changes from frame to frame. However, if bigger load changes happen, it can adjust pretty quickly. Thanks to that quirky feedback architecture it even works with a 250msec resolution. Usually the resolution of crap timers isn't that bad tho. With Win9x the resolution of the "ticks" (getticks(), System.currentTimeMillis() and the like) is 50-55msec.

This capping scheme was used for Fuzetsu and other Java 1.4 compatible 4k games.

Don't use this kind of scheme if you got a resolution of <=1msec. There are far better schemes with higher accuracy. Additionally they won't give you 100% CPU usage. :)

Comments

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options