Jump to content

  • Log In with Google      Sign In   
  • Create Account


Game Loop timings coming up slow?


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
10 replies to this topic

#1 bombshell93   Members   -  Reputation: 198

Like
0Likes
Like

Posted 22 August 2012 - 12:57 PM

I'm giving android development a go, just for the sake of trying it, but I'm getting a slow game loop.
Target FPS is 60 but I'm getting results returned 24 - 26 FPS instead, I've probably made a stupid mistake in measuring the time or something, but for the life of me I can't find the problem.
I've gone with an un-throttled Update and a throttled draw, most examples I saw used Thread.Sleep , but I've always been told its an unhealthy practice, so I've steered clear.
Here is the game loop. Update and Draw are currently empty.
@Override
public void run() {
  Canvas canvas = null;

  long updateCount = 0L;
  long updateTime = 0L;
  long tickCount = 0L;
  long tickTime = 0L;

  long tickLoopStart = 0L;
  long updateLoopStart = 0L;
  long elapsedNanoseconds = 0L;

  double timeDelta = 0;


  while (running)
  {
   canvas = null;
  
   tickCount++;
   tickLoopStart = System.nanoTime();
   try
   {
	canvas = surfaceHolder.lockCanvas();
	updateLoopStart = System.nanoTime();
	elapsedNanoseconds = System.nanoTime() - tickLoopStart;
  
	while (elapsedNanoseconds < NANOSECONDS_PER_DRAW)
	{
	 updateCount++;
	 Update(timeDelta);
	 timeDelta = (System.nanoTime() - updateLoopStart) / 1000000000;
	 updateLoopStart = System.nanoTime();
	 elapsedNanoseconds = System.nanoTime() - tickLoopStart;
	}
	updateTime += System.nanoTime() - tickLoopStart;
	updateLoopStart = System.nanoTime();
  
	Draw(canvas);
   }
   finally
   {
	if (canvas != null)
	{
	 surfaceHolder.unlockCanvasAndPost(canvas);
	}
   }
   elapsedNanoseconds = System.nanoTime() - tickLoopStart;
   tickTime += elapsedNanoseconds;
  
   timeDelta = (System.nanoTime() - updateLoopStart) / 1000000000;
  }
  Log.d(TAG, "Game loop has run " + tickCount + " times. Averaging " + (tickTime / tickCount) + "ns per loop. with a target of " + NANOSECONDS_PER_DRAW + "ns.");
  Log.d(TAG, "Update has run " + updateCount + " times. Averaging " + (updateTime / updateCount) + "ns per loop. taking up a total of " + updateTime + "ns.");
  Log.d(TAG, "Draw has run " + tickCount + " times. Averaging " + ((tickTime - updateTime) / tickCount) + "ns per loop. taking up a total of " + (tickTime - updateTime) + "ns.");
}

Any and all help is greatly appreciated,
Thanks in advanced,
Bombshell

Sponsor:

#2 bombshell93   Members   -  Reputation: 198

Like
0Likes
Like

Posted 23 August 2012 - 03:32 AM

I've been playing with it and I'm getting closer rates with this loop, but it cant take much load on the update,
Results atm are 30 FPS gets about 28 fps, 60 FPS target gets about 18 fps?
here is the loop as is,
@Override
public void run() {
  Canvas canvas = null;
 
  long updateCount = 0L;
  long updateTime = 0L;
  long tickCount = 0L;
  long tickTime = 0L;
 
  long tickLoop = 0L;
  long drawTime = 0L;
  long updateLoop = 0L;
  boolean hasUpdated = false;
  long elapsedNanoseconds = 0L;
 
  double timeDelta = 0;
 
 
  while (running)
  {
   canvas = null;
  
   tickCount++;
   tickLoop = System.nanoTime();
   updateLoop = System.nanoTime();
   elapsedNanoseconds = System.nanoTime() - tickLoop;
  
   while (elapsedNanoseconds < NANOSECONDS_PER_DRAW - drawTime || !hasUpdated)
   {
    updateCount++;
    Update(timeDelta / 1000000000);
   
    timeDelta = System.nanoTime() - updateLoop;
    updateLoop = System.nanoTime();
    elapsedNanoseconds = System.nanoTime() - tickLoop;
    hasUpdated = true;
   }
   hasUpdated = false;
   updateTime += System.nanoTime() - tickLoop;
   updateLoop = System.nanoTime();
  
   try
   {
    canvas = surfaceHolder.lockCanvas();
    Draw(canvas);
   }
   finally
   {
    if (canvas != null)
    {
	 surfaceHolder.unlockCanvasAndPost(canvas);
    }
   }
   elapsedNanoseconds = System.nanoTime() - tickLoop;
   tickTime += elapsedNanoseconds;
  
   timeDelta = System.nanoTime() - updateLoop;
   drawTime = (tickTime - updateTime) / tickCount;
  
   if (tickTime >= 20000000000L)
   {
    setRunning(false);
    ((Activity)gamePanel.getContext()).finish();
   }
  }
  Log.d(TAG,"Total run time " + tickTime + "ns. Averaging " + (1 / ( (double)(tickTime / tickCount) / 1000000000)) + " FPS.");
  Log.d(TAG, "Game loop has run " + tickCount + " times. Averaging " + (tickTime / tickCount) + "ns per loop. with a target of " + NANOSECONDS_PER_DRAW + "ns.");
  Log.d(TAG, "Update has run " + updateCount + " times. Averaging " + (updateTime / updateCount) + "ns per loop. taking up a total of " + updateTime + "ns.");
  Log.d(TAG, "Draw has run " + tickCount + " times. Averaging " + ((tickTime - updateTime) / tickCount) + "ns per loop. taking up a total of " + (tickTime - updateTime) + "ns.");
}

private void Update(double timeDelta)
{
  for (int i = 0; i < 64; i++)
  {
   for (int j = 0; j < 64; j++)
   {
    long foo = i + j + 1;
    foo *= foo;
    foo += foo;
    foo /= foo;
   }
  }
}

private void Draw(Canvas canvas)
{
}


#3 SimonForsman   Crossbones+   -  Reputation: 5971

Like
2Likes
Like

Posted 23 August 2012 - 04:55 AM

Sleep is not a unhealthy practice on mobiles, it is considered a bad idea for fullscreen AAA console or PC games where you can eat up whatever resources the system has without any negative consequences.

For mobiles you want to sleep as much as you can (without degrading the user experience) in order to preserve the devices battery.
I don't suffer from insanity, I'm enjoying every minute of it.
The voices in my head may not be real, but they have some good ideas!

#4 bombshell93   Members   -  Reputation: 198

Like
0Likes
Like

Posted 23 August 2012 - 05:36 AM

okay, taking that into account I've made this loop (this time I've commented it for convenience.
NANOSECONDS_PER_LOOP is calculated via typical, 1000000000 / TARGET_FPS. TARGET_FPS at the moment is 60,
though I'm getting anything from 12 to 20 FPS
have I done something wrong? or could it not be emulating properly?
@Override
public void run()
{
  Canvas canvas = null;
 
  long loopStart = 0L;
  long sleepTime = 0L;
 
  long timer = 0L;
  long tickTime = 0L;
  long tickCount = 0L;
 
  while (running)
  {
   loopStart = System.nanoTime(); //set loop start
   canvas = null; //reset canvas
   try
   {
    canvas = surfaceHolder.lockCanvas(); //get canvas, update, draw
    Update();
    Draw(canvas);
   
   }
   finally
   {
    if (canvas != null)
    { surfaceHolder.unlockCanvasAndPost(canvas); } //release canvas
   }
  
   if (timer >= 1000000000L) //each second display FPS
   {
    Log.d(TAG, 1/((double)(tickTime/tickCount)/1000000000) + " FPS"); // FPS
    tickTime = 0L;
    tickCount = 0L;
    timer = 0L;
   }
  
   sleepTime = NANOSECONDS_PER_LOOP - (System.nanoTime() - loopStart); //sleep time, ideal loop time - time already passed.
  
   if (sleepTime > 0)
   {
    try
    { Thread.sleep(sleepTime / 1000000); } //convert sleep time into milliseconds and sleep.
    catch (Exception e)
    {}
   }
  
   while (sleepTime < 0) //if lagging catch up.
   {
    Update();
    sleepTime += NANOSECONDS_PER_LOOP;
   }
  
   timer += System.nanoTime() - loopStart;
   tickTime += System.nanoTime() - loopStart;
   tickCount++;
  }
}

private void Update()
{
  for (int i = 0; i < 64; i++)
  {
   for (int j = 0; j < 64; j++)
   {
    long foo = i + j + 1;
    foo *= foo;
    foo += foo;
    foo /= foo;
   }
  }
}

private void Draw(Canvas canvas)
{
}


#5 SimonForsman   Crossbones+   -  Reputation: 5971

Like
1Likes
Like

Posted 23 August 2012 - 06:15 AM

remember that sleep will sleep for ATLEAST the time specified, it can and usually will sleep for longer.

Also , its a good idea to add the elapsedtime to the timer rather than reseting it at the start.

Since you are running a single thread you want something like:

lastTickTime = currentTime();
timePerTick = 1000.0 / updatesPerSecond;
while(running) {
	 curTime = currentTime();
	 while (curTime > lastTickTime+timePerTick) {
		 update();
		 lastTickTime+=timePerTick;
	 }
	 render();
}

This should be good enough, If your render framerate is capped by v-sync (I've never written a singlethreaded Android app so i always sleep in the update threads while the renderer runs as fast as it can, capped by the displays v-sync).

If this causes your app to render at more than 60 fps(no v-sync) you can add a timer check for the render function aswell and sleep for one ms or so if there is alot of time left until the renderer should run. (If the renderer should run soon its better to skip the sleep and just run the loop again since the sleep only specifies the minimum amount of time to sleep for)

Edited by SimonForsman, 23 August 2012 - 06:49 AM.

I don't suffer from insanity, I'm enjoying every minute of it.
The voices in my head may not be real, but they have some good ideas!

#6 bombshell93   Members   -  Reputation: 198

Like
0Likes
Like

Posted 23 August 2012 - 08:59 AM

it seems the only good results I get are with a while loop, which loops doing nothing until its time to work.
any time I try using sleep it over sleeps, even when I use Thread.sleep(1);

EDIT: its worth noting it doesn't oversleep a little, it oversleeps a whole other game loops worth

Edited by bombshell93, 23 August 2012 - 09:00 AM.


#7 SimonForsman   Crossbones+   -  Reputation: 5971

Like
1Likes
Like

Posted 23 August 2012 - 09:29 AM

it seems the only good results I get are with a while loop, which loops doing nothing until its time to work.
any time I try using sleep it over sleeps, even when I use Thread.sleep(1);

EDIT: its worth noting it doesn't oversleep a little, it oversleeps a whole other game loops worth


Are you testing in the emulator on Windows or on a real Android device ?

Android can run apps with realtime scheduling and shouldn't oversleep by much while Windows (aswell as Mac and Desktop Linux) will oversleep constantly. (Are you using a SurfaceView or something else for the rendering ?)

The main thing to take care of with Android is to make sure the garbage collector doesn't run at the wrong time (if you got garbage to clean up it will try to do so when you sleep), holding on to your references until you hit for example the end of a level and then drop them and force a garbage collection is a very good idea.

Edited by SimonForsman, 23 August 2012 - 09:33 AM.

I don't suffer from insanity, I'm enjoying every minute of it.
The voices in my head may not be real, but they have some good ideas!

#8 bombshell93   Members   -  Reputation: 198

Like
0Likes
Like

Posted 23 August 2012 - 11:18 AM

I'm using windows emulator, I don't have full access to an android device (I can get a hold of one but its not my own so I cant depend on it for the whole development process)
I am using SurfaceView, I considered using GLSurfaceView, but was advised until such a time that I need its functionality or power boost I should stick with SurfaceView.
though at the moment I'm not rendering anything, the entirety of the game loop is above, empty draw method and some filler logic in the update method for the sake of seeing how the loop acts under varying stress.

The game I intend on making isn't anything complicated, AABB collision detection, 1 stroke tracking, only background, tiles, player and some puzzle elements to draw. So I don't need an abundance of power, is there any practical way around the issue of over sleeping?

#9 SimonForsman   Crossbones+   -  Reputation: 5971

Like
1Likes
Like

Posted 23 August 2012 - 01:41 PM

is there any practical way around the issue of over sleeping?


Yes, run it on an Android device. (or a Linux distribution configured for the task)

The average Windows computer can run ~2-8 threads at any given time and will forcibly switch threads every 10-16ms, if your thread sleeps Windows will let something else run and it can take quite some time before it decides to run your thread again. (You might have over 300 threads active on a Windows system at any given time and while most of them are low priority background services(that won't get swapped in very often and when they do get swapped in they'll sleep very quickly again so other threads can use most of their timeslice) some of them are running at the same priority as your thread and will take as much time as they can when they get swapped in (which is what causes oversleeping).

You could also start a small c or c++ application that changes windows timeslice size using the timeBeginPeriod function, (you can push it down to 1ms if you want).
(Making the scheduler run more often will make sleep more accurate and the system more responsive but it will also reduce overall performance as the OS will spend more time swapping applications and threads in and out and less time letting them actually run. and then raise the process priority of the emulator process to high (can be done from the task manager)

On Android things are very different, the foreground application is the only high priority process and there are very few background threads running so sleep is reasonably accurate there. (Thus you don't really have to worry too much about it oversleeping in the emulator, unless it gets in the way of development)

Edited by SimonForsman, 23 August 2012 - 02:00 PM.

I don't suffer from insanity, I'm enjoying every minute of it.
The voices in my head may not be real, but they have some good ideas!

#10 bombshell93   Members   -  Reputation: 198

Like
0Likes
Like

Posted 23 August 2012 - 03:12 PM

would it really oversleep by a rather consistent 66ms?
5 I could deal with 10 I could deal with 15 - 20 is the expected, but over 60 ms?
with 30FPS needing 33ms loops 60ms is a dramatic frame drop.

how much difference would using a simple while(under ideal frame length) loop make?
and would it be plausible to use the while loop as I build the game up on windows and then swap to sleep in later development where I may test it on an android device?

Edited by bombshell93, 23 August 2012 - 03:13 PM.


#11 SimonForsman   Crossbones+   -  Reputation: 5971

Like
1Likes
Like

Posted 23 August 2012 - 03:29 PM

would it really oversleep by a rather consistent 66ms?
5 I could deal with 10 I could deal with 15 - 20 is the expected, but over 60 ms?
with 30FPS needing 33ms loops 60ms is a dramatic frame drop.

how much difference would using a simple while(under ideal frame length) loop make?
and would it be plausible to use the while loop as I build the game up on windows and then swap to sleep in later development where I may test it on an android device?


With the emulator nothing is strange, yes you can leave out the sleeping for now if it causes problems with the emulator (its only purpose is to avoid draining the battery afterall),

a simple while loop should make things more stable with the emulator, it might still be hard to hit 60fps in the emulator though (atleast once your app starts doing things), The emulator is very slow (+ you're most likely running the emulator with a debugger attached which slows it down even more)
I don't suffer from insanity, I'm enjoying every minute of it.
The voices in my head may not be real, but they have some good ideas!




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS