RateMonitor { public double getRate() { long duration = getDuration(); if (_numTicks > 1000000000) { _rate = 1000000000 * ((double)_numTicks / (double) duration ); } else { _rate = _numTicks * 1000000000.0 / duration; } return _rate; } RateMonitor(String name); boolean started(); void suspend(); void resume(); void start(); void tick(); void ticks(long ticks); double getRate(); long getDuration(); long getNumTicks(); void stop(); @Override String toString(); State getState(); boolean isStarted(); long getNanoTime(); void sleep(long msec);  }
@Test public void testGetRate() { RateMonitor monitor = new RateMonitor("test"); long startTime = System.nanoTime(); monitor.start(); for (int i = 0; i < 1000; ++i) { monitor.tick(); trySleep(1); } long endTime = System.nanoTime(); double monitorRate = monitor.getRate(); double calculatedRate = 1000 * 1000000000.0 / (endTime - startTime); String rateStr = monitor.toString(); assertTrue("CalculatedRate = " + calculatedRate + " : MonitorRate = " + monitorRate, Math.abs(calculatedRate - monitorRate) < 5); assertTrue("Monitor = " + rateStr,rateStr.contains("state = STARTED")); monitor = new RateMonitor("test"); startTime = System.nanoTime(); monitor.start(); for (int i = 0; i < 1000; ++i) { monitor.tick(); trySleep(1); } endTime = System.nanoTime(); monitor.suspend(); trySleep(100); monitorRate = monitor.getRate(); calculatedRate = 1000 * 1000000000.0 / (endTime - startTime); rateStr = monitor.toString(); assertTrue("CalculatedRate = " + calculatedRate + " : MonitorRate = " + monitorRate, Math.abs(calculatedRate - monitorRate) < 5); assertTrue("Monitor = " + rateStr,rateStr.contains("state = SUSPENDED")); long startTime2 = System.nanoTime(); monitor.resume(); for (int i = 0; i < 200; ++i) { monitor.tick(); trySleep(1); } long endTime2 = System.nanoTime(); monitorRate = monitor.getRate(); calculatedRate = 1200 * 1000000000.0 / ((endTime - startTime) + (endTime2 - startTime2)); rateStr = monitor.toString(); assertTrue("CalculatedRate = " + calculatedRate + " : MonitorRate = " + monitorRate, Math.abs(calculatedRate - monitorRate) < 5); assertTrue("Monitor = " + rateStr,rateStr.contains("state = RESUMED")); endTime2 = System.nanoTime(); monitor.stop(); calculatedRate = 1200 * 1000000000.0 / ((endTime - startTime) + (endTime2 - startTime2)); rateStr = monitor.toString(); assertTrue("CalculatedRate = " + calculatedRate + " : MonitorRate = " + monitorRate, Math.abs(calculatedRate - monitorRate) < 5); assertTrue("Monitor = " + rateStr,rateStr.contains("state = STOPPED")); trySleep(500); String rateStr2 = monitor.toString(); assertEquals("STOP State :" + rateStr2, rateStr, rateStr2); System.out.println("Done !!"); }