RefreshRateEstimator { public void addSample(long millis) { final long delta = millis - lastMillis; if (0 <= lastMillis && 0 < delta && delta < 62000L) { final float newRefreshRate = 1000f / delta; final boolean missed = 2 * newRefreshRate - epsilon < refreshRate && refreshRate < 2 * newRefreshRate + epsilon; if (refreshRate == 0) { refreshRate = newRefreshRate; } else if (missed && missedCount == 0) { missedCount++; } else { missedCount = 0; refreshRate += (newRefreshRate - refreshRate) * 0.5f; } if (refreshRate < 0 || Double.isNaN(refreshRate) || Double.isInfinite(refreshRate)) { Exceptions.report(new Exception("Invalid refresh rate, delta = " + delta + " refreshRate = " + refreshRate)); refreshRate = 0; } } lastMillis = millis; }  void addSample(long millis); public float refreshRate; }
@Test public void init1hz() { RefreshRateEstimator estimator = new RefreshRateEstimator(); estimator.addSample(0); estimator.addSample(1000); assertEquals(1.0, estimator.refreshRate, 0.01); estimator.addSample(2000); estimator.addSample(3000); assertEquals(1.0, estimator.refreshRate, 0.01); }
@Test public void init5hz() { RefreshRateEstimator estimator = new RefreshRateEstimator(); estimator.addSample(0); estimator.addSample(200); assertEquals(5.0, estimator.refreshRate, 0.01); estimator.addSample(400); estimator.addSample(600); assertEquals(5.0, estimator.refreshRate, 0.01); }
@Test public void initDuplicate() { RefreshRateEstimator estimator = new RefreshRateEstimator(); estimator.addSample(200); estimator.addSample(200); estimator.addSample(400); assertEquals(5.0, estimator.refreshRate, 0.01); estimator.addSample(600); estimator.addSample(800); assertEquals(5.0, estimator.refreshRate, 0.01); }
@Test public void missingSample() { RefreshRateEstimator estimator = new RefreshRateEstimator(); estimator.addSample(0); estimator.addSample(200); estimator.addSample(400); assertEquals(5.0, estimator.refreshRate, 0.01); estimator.addSample(800); assertEquals(5.0, estimator.refreshRate, 0.01); }
@Test public void halfRefreshRate() { RefreshRateEstimator estimator = new RefreshRateEstimator(); estimator.addSample(0); estimator.addSample(500); estimator.addSample(1000); assertEquals(2.0, estimator.refreshRate, 0.01); estimator.addSample(2000); assertEquals(2.0, estimator.refreshRate, 0.01); estimator.addSample(3000); assertEquals(1.0, estimator.refreshRate, 0.5); estimator.addSample(4000); assertEquals(1.0, estimator.refreshRate, 0.25); estimator.addSample(5000); estimator.addSample(6000); assertEquals(1.0, estimator.refreshRate, 0.1); estimator.addSample(7000); estimator.addSample(8000); estimator.addSample(9000); assertEquals(1.0, estimator.refreshRate, 0.01); }