• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Bombshell93

Game Loop timings coming up slow?

10 posts in this topic

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.
[CODE]
@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.");
}
[/CODE]

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

Share this post


Link to post
Share on other sites
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,
[CODE]
@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)
{
}
[/CODE]
0

Share this post


Link to post
Share on other sites
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.
2

Share this post


Link to post
Share on other sites
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?
[CODE]
@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)
{
}
[/CODE]
0

Share this post


Link to post
Share on other sites
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:

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

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 [b]one ms [/b]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
1

Share this post


Link to post
Share on other sites
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
0

Share this post


Link to post
Share on other sites
[quote name='bombshell93' timestamp='1345733964' post='4972593']
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
[/quote]

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
1

Share this post


Link to post
Share on other sites
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?
0

Share this post


Link to post
Share on other sites
[quote name='bombshell93' timestamp='1345742296' post='4972661']
is there any practical way around the issue of over sleeping?
[/quote]

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
1

Share this post


Link to post
Share on other sites
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
0

Share this post


Link to post
Share on other sites
[quote name='bombshell93' timestamp='1345756368' post='4972751']
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?
[/quote]

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)
1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0