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);
}
asked Nov 5, 2014 at 21:47
\$\endgroup\$

1 Answer 1

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.

answered Nov 5, 2014 at 21:55
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.