public class Timer {
private long timeThen;
private static final long measureInterval = 1000 * 1000000L; // one second
private long lastMeasure = System.nanoTime();
private int frameCounter;
private long fps;
/**
* Creates a new Timer.
*/
public Timer() {
timeThen = System.nanoTime();
}
/**
* Attempts to sync the timer with the specified fps.
* @param fps the fps to sync with.
*/
public void sync(int fps) {
updateFPS();
long gapTo = 1000000000L/fps + timeThen;
long timeNow = System.nanoTime();
try {
while (gapTo > timeNow) {
Thread.sleep((gapTo-timeNow) / 5000000000L);
timeNow = System.nanoTime();
}
} catch (Exception e) {}
timeThen = timeNow;
}
/**
* Calculates the fps.
*/
private void updateFPS() {
this.frameCounter++;
long now = System.nanoTime();
if(now >= this.lastMeasure + measureInterval) {
this.fps = this.frameCounter;
this.frameCounter = 0;
this.lastMeasure += measureInterval;
}
}
/**
* The Timer automatically tries to calculate the fps it's running on.
* This method returns that value. It updates once every second.
* @return the current fps this timer is running in.
*/
public long getFps() {
return this.fps;
}
}