Game loop and frames per second

Hi y’all I see some strange things happening when I use the following code to create a game loop:

private static final int MAX_CPS = 50;
private static final int MS_PER_FRAME = 1000 / MAX_CPS;

public void run()
{
while (running)
{
long cycleStartTime = System.currentTimeMillis();

repaint();

if (System.currentTimeMillis() - lastCPSTime > 1000)
{
  lastCPSTime = System.currentTimeMillis();
  cps = cyclesThisSecond;
  cyclesThisSecond = 0;
}
else
  cyclesThisSecond++;

long timeSinceStart = (System.currentTimeMillis() - cycleStartTime);
if (timeSinceStart < MS_PER_FRAME)
{
  try
  {
    Thread.sleep(MS_PER_FRAME - timeSinceStart);
  }
  catch (InterruptedException e) {}
}

}
}

As you can see, it’s just a regular gameloop. The variable cps is drawn to screen every second.
However when I set MAX_CPS=50, cps has the value of 32. When MAX_CPS=40, then cps is still 32! When MAX_CPS=30 then cps is 20. When MAX_CPS=65 then cps is 65! When MAX_CPS=100, then cps is still 65!

I can understand there’s some overhead in using the Thread.sleep statement, but this behaviour I cannot explanin.

Can somebody shine a light on this?

Thanx!
Ronnie

currentTimeMillis has a resolution of ~50ms on Win9x, and ~10ms in WinNT>.

Thread.sleep() doesn’t have an outstanding accuracy either.

Without having a closer look at your loop, I can’t say for sure if that is the cause though…
I never bother with sleep myself, better to hope for vsync, or tight loop on the timer. =)

:edit:

oh heyup, this is in the J2ME forum isn’t it =)

Tight loop on the timer then.
(shame MIDP2.0 gave us a load of substandard ‘game API’ classes, instead of useful stuff like a method to expose the vblank signal)