sorry for too many questions, but here it goes…
import sun.misc.Perf;
public class HiResTimer {
private Perf hiResTimer;
private long freq;
public HiResTimer() {
hiResTimer = Perf.getPerf();
freq = hiResTimer.highResFrequency();
// System.out.println("freq=" + freq);
// System.out.println("counter=" + hiResTimer.highResCounter() );
}
public long currentTimeMillis() {
// hmm...why do we have to divide counter with freq???
return hiResTimer.highResCounter() * 1000 / freq;
// return System.currentTimeMillis();
}
public static void main(String[] args) {
int counter = 0;
long duration = (long)(Double.parseDouble(args[0]) * 1000);
final int fps = Integer.parseInt(args[1]);
final HiResTimer hrt = new HiResTimer();
long startTime = hrt.currentTimeMillis();
long endTime = startTime + duration;
long newTime;
do {
long oldTime = hrt.currentTimeMillis();
// render here, do your stuff
counter++;
newTime = hrt.currentTimeMillis();
long renderTime = newTime - oldTime;
// hmm.., is sleep precise enough???
if (renderTime < (1000 / fps) ) {
try { Thread.sleep(1000 / fps - renderTime);
} catch (Exception ex) { }
}
} while (newTime < endTime);
System.out.println("counter=" + counter);
System.out.println("duration=" + (newTime - startTime) );
}
}
To testrun it in JRE1.4.2:
Java HiResTimer 10.5 30
I would like to have your comments on implementing a main loop in java game. Do you think this code is properly implemented?
What is the best known fps to give a smooth updates, how do I identify the optimal fps on clientside at runtime?
Should we delete division math in currentTimeMillis() method, do we need it?
Is it always best to implement so that it will run on fixed fps and will sleep until ticktime is done. Is thread.sleep(x) precise enough here?
Do you mind publishing your mainloop code.
thx
ps: This code is influensed by Abuse post.