\$\begingroup\$
\$\endgroup\$
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
1 Answer 1
\$\begingroup\$
\$\endgroup\$
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
lang-java