1 /* 2 * Copyright (c) 2009-2010 jMonkeyEngine 3 * All rights reserved. 4 * 5 * Redistribution and use in source and binary forms, with or without 6 * modification, are permitted provided that the following conditions are 7 * met: 8 * 9 * * Redistributions of source code must retain the above copyright 10 * notice, this list of conditions and the following disclaimer. 11 * 12 * * Redistributions in binary form must reproduce the above copyright 13 * notice, this list of conditions and the following disclaimer in the 14 * documentation and/or other materials provided with the distribution. 15 * 16 * * Neither the name of 'jMonkeyEngine' nor the names of its contributors 17 * may be used to endorse or promote products derived from this software 18 * without specific prior written permission. 19 * 20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 21 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 22 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 23 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 24 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 25 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 26 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 27 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 28 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 29 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 30 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 31 */ 32 33 package com.jme3.system; 34 35 /** 36 * <code>NanoTimer</code> is a System.nanoTime implementation of <code>Timer</code>. 37 * This is primarily useful for headless applications running on a server. 38 * 39 * @author Matthew D. Hicks 40 */ 41 public class NanoTimer extends Timer { 42 43 private static final long TIMER_RESOLUTION = 1000000000L; 44 private static final float INVERSE_TIMER_RESOLUTION = 1f/1000000000L; 45 46 private long startTime; 47 private long previousTime; 48 private float tpf; 49 private float fps; 50 51 public NanoTimer() { 52 startTime = System.nanoTime(); 53 } 54 55 /** 56 * Returns the time in seconds. The timer starts 57 * at 0.0 seconds. 58 * 59 * @return the current time in seconds 60 */ 61 @Override 62 public float getTimeInSeconds() { 63 return getTime() * INVERSE_TIMER_RESOLUTION; 64 } 65 66 public long getTime() { 67 return System.nanoTime() - startTime; 68 } 69 70 public long getResolution() { 71 return TIMER_RESOLUTION; 72 } 73 74 public float getFrameRate() { 75 return fps; 76 } 77 78 public float getTimePerFrame() { 79 return tpf; 80 } 81 82 public void update() { 83 tpf = (getTime() - previousTime) * (1.0f / TIMER_RESOLUTION); 84 fps = 1.0f / tpf; 85 previousTime = getTime(); 86 } 87 88 public void reset() { 89 startTime = System.nanoTime(); 90 previousTime = getTime(); 91 } 92 } 93