1
\$\begingroup\$

How can I improve this main game loop that monitors and displays frames per second?

    public void run() {
    running=true;
    initengine();
    initgame();
    //Initialise game loop
    long looptime, difference=0,timetaken=0;
    int frames=0;
    fps=0;
    //Main game Loop
    while(running){
        while (timetaken < 1000 ){   
        looptime=System.currentTimeMillis();

           update();
           render();

           try {
                Thread.sleep(1);
            } catch (InterruptedException ex) {
                System.out.println("Error");
            }

            frames++;
            timetaken+=difference;
            difference=(System.currentTimeMillis()-looptime); 
        }
        fps=frames;
        frames=0;
        timetaken=0;
    }        
System.exit(0);

}
\$\endgroup\$
2
\$\begingroup\$

A Thread.sleep(...) in the middle of your game loop is a problem. No-one wants to see that.

A really simple solution to this problem is do things a little differently....

long nextSecond = System.currentTimeMillis() + 1000;
int frames = 0;
while (running) {

    ....
    // Do your game loop work...
    ....

    frames++;
    long now = System.currentTimeMillis();
    if (now > nextSecond) {
        fps = frames;
        frames = 0;
        nextSecond = now + 1000;
    }
}

This removes the sleep, and the nested loop.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.