Skip to content

Instantly share code, notes, and snippets.

@michael-wang
Created October 30, 2013 01:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michael-wang/7226008 to your computer and use it in GitHub Desktop.
Save michael-wang/7226008 to your computer and use it in GitHub Desktop.
public class FrameRateCalculator extends Observable {
private static final long DEFAULT_NOTIFY_INTERVAL = 1000L;
public FrameRateCalculator() {
this(DEFAULT_NOTIFY_INTERVAL);
}
public FrameRateCalculator(long notifyObserverIntervalInMs) {
NOTIFY_OBSERVER_INTERVAL = notifyObserverIntervalInMs;
}
public void start() {
startTime = System.currentTimeMillis();
count = 0;
}
public void addFrame() {
count++;
final long now = System.currentTimeMillis();
final long elapsed = now - startTime;
if (elapsed > NOTIFY_OBSERVER_INTERVAL) {
final float fps = calculateFPS(elapsed, count);
setChanged();
notifyObservers(fps);
start();
}
}
private float calculateFPS(long duration, long frameCount) {
return (frameCount * 1000L / duration);
}
private final long NOTIFY_OBSERVER_INTERVAL;
private long startTime;
private long count;
}
@michael-wang
Copy link
Author

Call start() when you want to track frame rate.
Call addFrame() when you draw a frame.
Implement java.util.Observer to receive frame rate.

Notice: you usually call addFrame on OpenGL thread, and then got observer callback, where you try to update UI (such as show fps on TextVIew), in this case you have to use Activity::runOnUiThread().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment