How do you measure fps?

How do you guys display FPS to the screen?

int fps = 60;
t0 = system.nanoTime();
//...lots of rendering
//..
//..
t1 = system.nanoTime();
long delta = ((1E+9)*1.0/fps) - (t1-t0);
g.drawString("FPS:"+ (1E+9)*1.0/delta, 0,0);
buffer.show();
//Sleep
Thread.sleep(delta)

This is how I currently do it and there are so many problems with it:

  • Delta may be negative due to bad resolution
  • Delta does NOT take into account time spent calling g.drawstring and buffer.show
  • The sleep may be accurate within margins of error by calling system.nanoTime() inside sleep() but this makes for inaccurate display
  • If t1 is too long delta becomes negative. Do you play catchup with the framerate by sleeping a shorter time next iteration?

I see no way of circumventing the second point, display to console would be much easier, you could wrap all of it in a method, measure time between each method-calls and print it to console. But any displayed FPS must take the delta THEN display it.

For your second point you can do this (making sure to initialise t0 to something):

int fps = 60;
//...lots of rendering
//..
//..
t1 = system.nanoTime();
long delta = ((1E+9)*1.0/fps) - (t1-t0);
t0 = system.nanoTime();
g.drawString("FPS:"+ (1E+9)*1.0/delta, 0,0);
buffer.show();
//Sleep
Thread.sleep(delta)

I usually just literally count the number of frames it displays in a second (the fps gets updated every second).

I just count the number of times per second the GLEventListener.display() method is called. And I use System.currentTimeMillis() - with each frame 16 - 40 ms to render I don’t think precision is that much of an issue.