Game speed keeps changing

Hi, I have a game loop like this:

while(true)
        {
            start = System.nanoTime();

            draw();
            if(inGame)update();
            while(System.nanoTime() - start <  31250000)
            {
            Thread.yield();
            }

Its a very simple loop for a lil application. However, when running it in both the IDE and as an executable jar, in runs at different speeds. Sometimes it runs normally, but often it’ll run slower than before. The speed dosnt change mid way - it’s either slow from start to end, or normal from start to end. Its a very simple program so it isnt just my CPU not being able to handle it. Is this a common problem, a fault with my loop or just my PC?

Try using Thread.sleep, instead.

Could also be a timing accuracy problem. Windows has a very inaccurate global timer, but a more accurate timer will be used when certain functions are called. Other running programs can have this better timer activated, which would affect your program. However, the main problem is that your program suffers so much from the bad timer accuracy, but on to that later.

To force the program to constantly run the high accuracy timer, create a thread and have it sleep forever in a loop at the start of your program.

    public static void startSleepFixThread(){
        new Thread("Sleep fix thread") {
        	{
                setDaemon(true);
        	}
            public void run() {
                try {
                    while(true){
                        Thread.sleep(Long.MAX_VALUE);
                    }
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
        }.start();
    }

Concerning the other problem (your program), it can be solved very easily. The problem is your start = System.nanoTime() line. Change your loop to this:


        long start = System.nanoTime();
        while(true){
            draw();
            if(inGame)update();

            long end = System.nanoTime();
            if(end - start <  31250000){
                try{
                    Thread.sleep((31250000 + start-end) / 1000000); //Sleep time in milliseconds
                catch(InterruptedException ex){
                    ex.printStackTrace();
                }

            start += 31250000; //No error build-up!
        }

And finally, why are you aiming for 32 FPS? Isn’t 60 or 50 more common and better looking?

The thread hack on Windows is only valid when using the system thread scheduler AFAIK - the nanotime timer is a different one. Thread.yield() I think is largely unaffected by the hack too - it fixes Thread.sleep().

Cas :slight_smile:

Hmm… Then why does he get so weird performance? Let’s see what OP says when he gets back…

Hey guys thanks for the replies

I tried the loop you proposed, not sure what to say…

I ran in 15 times. 3 of which it ran at the normal ‘intended’ speed, 11 times it ran at the slower speed, again the same as seen before with the last loop. 1 time it ran at an insanely fast speed, everything was whizzing across the screen, havnt seen that before ^^. How the hell can the same code run at such varying speeds?

I’m starting to wonder if it’s something I’ve done wrong with my setup. If I change the time for it to wait, to say, 10000 or even 0, the majority of times I run it it STILL goes at this slow speed, only occasionally going at the new speed.

[quote]class main extends JFrame implements KeyListener
[/quote]

[quote]public main()
{
super(“Name”);
this.setSize(1130,700);
this.setResizable(false);
this.setIgnoreRepaint(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.addKeyListener(this);
createBufferStrategy(2);
bs = getBufferStrategy();
[/quote]
There’s nothing stupid here is there?

No reason in particular for the 32fps. Its got little that moves and is slow moving at that. Is just a demo for some concept.

Here’s my pretty gameloop: http://www.java-gaming.org/topics/solving-stuttering-with-fixed-timesteps-once-and-for-all/24975/msg/213649/view.html#msg213649

And what exactly goes on in the draw and update methods?

The draw method:

Graphics2D g2 = (Graphics2D)bs.getDrawGraphics();
Then I use this to draw the GUI, and draw all the NPC sprites. its pretty much
for(int i = 0; i < number; i++)
npc[i].draw(g2);

basically.

The update method is just the same, but the update makes a decision for the npc (just random number chooses action) then sets its velocity, or if a move is chosen it just moves the NPC around the screen.

It’s only simple logic going on in the update, I can’t think of anything that could do this. Nothing special at all.

It’s worth noting that the timer used by System.nanoTime(), on certain motherboards, CPUs and OS combinations, can randomly change speed depending on CPU power settings. That’s why we don’t use it ourselves and rely on the slightly lower-resolution timer from LWJGL.

Cas :slight_smile:

I changed my game loop to

while(true)
{

draw
update
}

No timers at all, and it still happens (hahaha). Sometimes insanely fast, sometimes slow. It turns out it is my draw method causing it, so sorry for wasting peoples time. Ive no idea what in there is doing it though, about to find out I hope.

[quote]t’s worth noting that the timer used by System.nanoTime(), on certain motherboards, CPUs and OS combinations, can randomly change speed depending on CPU power settings. That’s why we don’t use it ourselves and rely on the slightly lower-resolution timer from LWJGL.
[/quote]
Interesting. That indicates that some implementations uses the clock cycle counter (x86 still have em?). May need to stop with the habit of using nanoTime().

What we all have to struggle with is that modern computers are not real time systems. But are/should be fast enough to fake it.

I read some article a few years ago by a professional game developer (ho ho ;)) about how it’s basically all a bit screwy, and you need to use 3 different clocks (the CPU clock, multimedia clock, and the system time) and use them to agree on actual time elapsed since last time using various heuristics and dead reckoning. It was all a bit hairy. We’ve found that the multimedia clock on Windows is pretty much 100% accurate to 1ms, and the system time on Linux and MacOS is 100% accurate to 1ms as well. The nanotimer has varying degrees of strangeness.

Cas :slight_smile:

Maybe you’re getting OpenGL acceleration randomly? I had so many problems with it that I’m just sticking to pure OpenGL.

I haven’t paid attention recently, but yeah, alot of speedstep machines (what, 10 yrs ago) didn’t account for changing of CPU speed for power/heat consumption and the counter reflected ‘actual’ CPU clockticks. Couple that with multicore machines where each physical CPU has it’s own counter = fun!

On some architectures and OS’s, Java’s scheduler will actually ignore an excessive number of Thread.yield calls called within a short time of each other. Looking at it a little deeper, it looks to just be Solaris that’s special-cased that way in the jvm code, but the OS itself may also have different ideas as to how to treat threads causing scheduler churn. Yield is really just a suggestion – if you really want a sleep, use sleep.

theagentd I think you must be right, because it was very rare, but perfect when whatever it was occured. The regular slowness was being caused by a scaling operation on an image every draw call

::slight_smile:

The OpenGL acceleration is so unreliable that it’s better to explicitly disable it and focus on making your game work with without it.