Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2011
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.48 KB | None | 0 0
  1. public class Timer {
  2.  
  3.     private long timeThen;
  4.  
  5.     private static final long measureInterval = 1000 * 1000000L; // one second
  6.     private long lastMeasure = System.nanoTime();
  7.     private int frameCounter;
  8.     private long fps;
  9.  
  10.     /**
  11.      * Creates a new Timer.
  12.      */
  13.     public Timer() {
  14.         timeThen = System.nanoTime();
  15.     }
  16.  
  17.     /**
  18.      * Attempts to sync the timer with the specified fps.
  19.      * @param fps the fps to sync with.
  20.      */
  21.     public void sync(int fps) {
  22.         updateFPS();
  23.  
  24.         long gapTo = 1000000000L/fps + timeThen;
  25.         long timeNow = System.nanoTime();
  26.  
  27.         try {
  28.             while (gapTo > timeNow) {
  29.                 Thread.sleep((gapTo-timeNow) / 5000000000L);
  30.                 timeNow = System.nanoTime();
  31.             }
  32.         } catch (Exception e) {}
  33.  
  34.         timeThen = timeNow;
  35.     }
  36.  
  37.     /**
  38.      * Calculates the fps.
  39.      */
  40.     private void updateFPS() {
  41.         this.frameCounter++;
  42.  
  43.         long now = System.nanoTime();
  44.         if(now >= this.lastMeasure + measureInterval) {
  45.            this.fps = this.frameCounter;
  46.            this.frameCounter = 0;
  47.            this.lastMeasure += measureInterval;
  48.         }
  49.     }
  50.  
  51.     /**
  52.      * The Timer automatically tries to calculate the fps it's running on.
  53.      * This method returns that value. It updates once every second.
  54.      * @return the current fps this timer is running in.
  55.      */
  56.     public long getFps() {
  57.         return this.fps;
  58.     }
  59.  
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement