Calculating and displaying FPS accurately and efficiently

I was wondering if anyone could show me any code where they have used a JPanel
with double buffering and active rendering using a thread and was able to accurately and effectively calculate and display their FPS.

Here is my code:

	/**
	 * Implements the Runnable interface. Responsible
	 * for updates, rendering, and sleeping the thread.
	 */
	@Override
	public void run()
	{
		bRunning = true;	// Keep flag set
		long beforeTime, deltaTime, sleepTime;
	
		beforeTime = System.currentTimeMillis();
		
		initRender();
		
		// Repeat update/animation loop, sleeping a bit
		while (bRunning)
		{
			
			try
			{
				updateBoard();
			} catch (IOException e)
			{ System.err.println("Error: IO Failure"); }
			
			renderBoard();
			paintBoard();
			
			deltaTime = System.currentTimeMillis() - beforeTime;
			sleepTime = PERIOD - deltaTime;
			
			if (sleepTime < 0)
			{
				timeOver = (-1) * (int) sleepTime;
				sleepTime = 0;
				
			}
			
			try
			{
				Thread.sleep(sleepTime);
			}
			catch(InterruptedException ie)
			{
				System.err.println("Error: Thread exception!");
			}
			beforeTime = System.currentTimeMillis();
		}
		
		System.exit(0);	// end of run
	}
	/**
	 * Renders the resulting output frame to
	 * an Image buffer. Off-screen rendering.
	 */
	private void renderBoard()
	{
		
		// Draw background, using correct coordinates
		gDevice.drawImage(background, bX[0], 0, null);
		gDevice.drawImage(background, bX[1], 0, null);
		gDevice.drawImage(background, bX[2], 0, null);
		gDevice.drawImage(background, bX[3], 0, null);
		
		// Draw characters and all sprites
		gChar.draw(gDevice);
		
		//  Test debug flags and take explicit action here
		if (bFPSDebug)
			calcAndDisplayFPS();
	}
	/**
	 * Used to calculate and paint the FPS on the GameBoard.
	 */
	private void calcAndDisplayFPS()
	{
		FPS = 1000 / ((Double) PERIOD + timeOver);
		gDevice.drawString("FPS: " + String.valueOf(FPS), 20, 20);
	}

This doesn’t seem to work as my output is constantly either 62.0 or 66.0. This is with a const PERIOD of 10 milliseconds. This means as long as my computer can handle it I should be sleeping for 10 milliseconds which should give me 1000/10 = 100 FPS cap. Apparently I am not achieving this.

Does anyone know if what I am doing is sufficient to get an accurate FPS count. And also is calculating and drawing to the screen every loop like this going to be a performance hit in itself?

If the

Hmm… for one, your timeOver seems to be updated only if you go over budget, so that’ll skew your computation if you dip over just once - since that value will be retained for the subsequent loops where you don’t go over.

Oh yes, I had timeOver as a class variable when it should have had a local scope. Now I have a constant 100.0 FPS. I don’t guess I should have any fluctuation at all?

Heres some code from Killer Game Programming in Java, that has all of your concerns.


import javax.swing.*;
import java.awt.*;
import java.text.DecimalFormat;


public class TilePanel extends JPanel implements Runnable
{
  private static final int PWIDTH = 500;   // size of panel
  private static final int PHEIGHT = 400; 

  private static long MAX_STATS_INTERVAL = 1000000000L;
  // private static long MAX_STATS_INTERVAL = 1000L;
    // record stats every 1 second (roughly)

  private static final int NO_DELAYS_PER_YIELD = 16;
  /* Number of frames with a delay of 0 ms before the animation thread yields
     to other running threads. */

  private static int MAX_FRAME_SKIPS = 5;   // was 2;
    // no. of frames that can be skipped in any one animation loop
    // i.e the games state is updated but not rendered

  private static int NUM_FPS = 10;
     // number of FPS values stored to get an average


  // used for gathering statistics
  private long statsInterval = 0L;    // in ns
  private long prevStatsTime;   
  private long totalElapsedTime = 0L;
  private long gameStartTime;
  private int timeSpentInGame = 0;    // in seconds

  private long frameCount = 0;
  private double fpsStore[];
  private long statsCount = 0;
  private double averageFPS = 0.0;

  private long framesSkipped = 0L;
  private long totalFramesSkipped = 0L;
  private double upsStore[];
  private double averageUPS = 0.0;


  private DecimalFormat df = new DecimalFormat("0.##");  // 2 dp
  private DecimalFormat timedf = new DecimalFormat("0.####");  // 4 dp


  private Thread animator;           // the thread that performs the animation
  private boolean running = false;   // used to stop the animation thread
  private boolean isPaused = false;

  private long period;                // period between drawing in _nanosecs_


  private Initialize ini;
  private TileMap tileMap;


  // used at game termination
  private boolean gameOver = false;
  private int score = 0;
  private Font font;
  private FontMetrics metrics;

  // off screen rendering
  private Graphics dbg; 
  private Image dbImage = null;



  public TilePanel(Initialize ini, long period)
  {
    this.ini = ini;
    this.period = period;

    setBackground(Color.white);
    setPreferredSize( new Dimension(PWIDTH, PHEIGHT));

    tileMap = new TileMap();

    // set up message font
    font = new Font("SansSerif", Font.BOLD, 10);
    metrics = this.getFontMetrics(font);

    // initialise timing elements
    fpsStore = new double[NUM_FPS];
    upsStore = new double[NUM_FPS];
    for (int i=0; i < NUM_FPS; i++) {
      fpsStore[i] = 0.0;
      upsStore[i] = 0.0;
    }
  }  // end of WormPanel()


  @Override
  public void addNotify()
  // wait for the JPanel to be added to the JFrame before starting
  { super.addNotify();   // creates the peer
    startGame();         // start the thread
  }


  private void startGame()
  // initialise and start the thread 
  { 
    if (animator == null || !running) {
      animator = new Thread(this);
	  animator.start();
    }
  } // end of startGame()
    

  // ------------- game life cycle methods ------------
  // called by the JFrame's window listener methods


  public void resumeGame()
  // called when the JFrame is activated / deiconified
  {  isPaused = false;  } 


  public void pauseGame()
  // called when the JFrame is deactivated / iconified
  { isPaused = true;   } 


  public void stopGame() 
  // called when the JFrame is closing
  {  running = false;   }

  // ----------------------------------------------


  public void run()
  /* The frames of the animation are drawn inside the while loop. */
  {
    long beforeTime, afterTime, timeDiff, sleepTime;
    long overSleepTime = 0L;
    int noDelays = 0;
    long excess = 0L;

    gameStartTime = Timer.getValue();
    prevStatsTime = gameStartTime;
    beforeTime = gameStartTime;

	running = true;

	while(running) {
	  gameUpdate();
      gameRender();
      paintScreen();

      afterTime = Timer.getValue();
      timeDiff = afterTime - beforeTime;
      sleepTime = (period - timeDiff) - overSleepTime;  

      if (sleepTime > 0) {   // some time left in this cycle
        try {
          Thread.sleep(sleepTime/1000000L);  // nano -> ms
        }
        catch(InterruptedException ex){}
        overSleepTime = (Timer.getValue() - afterTime) - sleepTime;
      }
      else {    // sleepTime <= 0; the frame took longer than the period
        excess -= sleepTime;  // store excess time value
        overSleepTime = 0L;

        if (++noDelays >= NO_DELAYS_PER_YIELD) {
          Thread.yield();   // give another thread a chance to run
          noDelays = 0;
        }
      }

      beforeTime = Timer.getValue();

      /* If frame animation is taking too long, update the game state
         without rendering it, to get the updates/sec nearer to
         the required FPS. */
      int skips = 0;
      while((excess > period) && (skips < MAX_FRAME_SKIPS)) {
        excess -= period;
	    gameUpdate();    // update state but don't render
        skips++;
      }
      framesSkipped += skips;

      storeStats();
	}

    printStats();
    System.exit(0);   // so window disappears
  } // end of run()


  private void gameUpdate() { 
    if (!isPaused && !gameOver) {
    }
  }  // end of gameUpdate()


  private void gameRender()
  {
    if (dbImage == null){
      dbImage = createImage(PWIDTH, PHEIGHT);
      if (dbImage == null) {
        System.out.println("dbImage is null");
        return;
      }
      else
        dbg = dbImage.getGraphics();
    }

    // clear the background
    dbg.setColor(Color.white);
    dbg.fillRect (0, 0, PWIDTH, PHEIGHT);

    dbg.setColor(Color.black);

    // draw game elements
    tileMap.draw(dbg);

    dbg.setColor(Color.blue);
    dbg.setFont(font);

    // report frame count & average FPS and UPS at top left
    // dbg.drawString("Frame Count " + frameCount, 10, 25);
    dbg.drawString("Average FPS/UPS: " + df.format(averageFPS) + ", " +
    df.format(averageUPS), 10, 10);  // was (10,55)

    if (gameOver)
      gameOverMessage(dbg);
  }  // end of gameRender()


  private void gameOverMessage(Graphics g)
  // center the game-over message in the panel
  {
    String msg = "Game Over. Your Score: " + score;
	int x = (PWIDTH - metrics.stringWidth(msg))/2; 
	int y = (PHEIGHT - metrics.getHeight())/2;
	g.setColor(Color.red);
    g.setFont(font);
	g.drawString(msg, x, y);
  }  // end of gameOverMessage()


  private void paintScreen()
  // use active rendering to put the buffered image on-screen
  { 
    Graphics g;
    try {
      g = this.getGraphics();
      if ((g != null) && (dbImage != null))
        g.drawImage(dbImage, 0, 0, null);
      g.dispose();
    }
    catch (Exception e)
    { System.out.println("Graphics context error: " + e);  }
  } // end of paintScreen()


  private void storeStats()
  /* The statistics:
       - the summed periods for all the iterations in this interval
         (period is the amount of time a single frame iteration should take), 
         the actual elapsed time in this interval, 
         the error between these two numbers;

       - the total frame count, which is the total number of calls to run();

       - the frames skipped in this interval, the total number of frames
         skipped. A frame skip is a game update without a corresponding render;

       - the FPS (frames/sec) and UPS (updates/sec) for this interval, 
         the average FPS & UPS over the last NUM_FPSs intervals.

     The data is collected every MAX_STATS_INTERVAL  (1 sec).
  */
  { 
    frameCount++;
    statsInterval += period;

    if (statsInterval >= MAX_STATS_INTERVAL) {     // record stats every MAX_STATS_INTERVAL
      long timeNow = Timer.getValue();
      timeSpentInGame = (int) ((timeNow - gameStartTime)/1000000000L);  // ns --> secs

      long realElapsedTime = timeNow - prevStatsTime;   // time since last stats collection
      totalElapsedTime += realElapsedTime;

      double timingError = 
         ((double)(realElapsedTime - statsInterval) / statsInterval) * 100.0;

      totalFramesSkipped += framesSkipped;

      double actualFPS = 0;     // calculate the latest FPS and UPS
      double actualUPS = 0;
      if (totalElapsedTime > 0) {
        actualFPS = (((double)frameCount / totalElapsedTime) * 1000000000L);
        actualUPS = (((double)(frameCount + totalFramesSkipped) / totalElapsedTime) 
                                                             * 1000000000L);
      }

      // store the latest FPS and UPS
      fpsStore[ (int)statsCount%NUM_FPS ] = actualFPS;
      upsStore[ (int)statsCount%NUM_FPS ] = actualUPS;
      statsCount = statsCount+1;

      double totalFPS = 0.0;     // total the stored FPSs and UPSs
      double totalUPS = 0.0;
      for (int i=0; i < NUM_FPS; i++) {
        totalFPS += fpsStore[i];
        totalUPS += upsStore[i];
      }

      if (statsCount < NUM_FPS) { // obtain the average FPS and UPS
        averageFPS = totalFPS/statsCount;
        averageUPS = totalUPS/statsCount;
      }
      else {
        averageFPS = totalFPS/NUM_FPS;
        averageUPS = totalUPS/NUM_FPS;
      }
/*
      System.out.println(timedf.format( (double) statsInterval/1000000000L) + " " + 
                    timedf.format((double) realElapsedTime/1000000000L) + "s " + 
			        df.format(timingError) + "% " + 
                    frameCount + "c " +
                    framesSkipped + "/" + totalFramesSkipped + " skip; " +
                    df.format(actualFPS) + " " + df.format(averageFPS) + " afps; " + 
                    df.format(actualUPS) + " " + df.format(averageUPS) + " aups" );
*/
      framesSkipped = 0;
      prevStatsTime = timeNow;
      statsInterval = 0L;   // reset
    }
  }  // end of storeStats()


  private void printStats()
  {
    System.out.println("Frame Count/Loss: " + frameCount + " / " + totalFramesSkipped);
	System.out.println("Average FPS: " + df.format(averageFPS));
	System.out.println("Average UPS: " + df.format(averageUPS));
    System.out.println("Time Spent: " + timeSpentInGame + " secs");
  }  // end of printStats()

}  // end of WormPanel class

I just copied it from an early project of mine, so you’re to do some edits and removing unused code.
All Timer.getVariable() calls, can be replaced with System.nanoTime() for the exact same effect.

Cheers!