diff --git a/java_console/io/src/main/java/com/rusefi/io/serial/RateCounter.java b/java_console/io/src/main/java/com/rusefi/io/serial/RateCounter.java new file mode 100644 index 0000000000..51c9594811 --- /dev/null +++ b/java_console/io/src/main/java/com/rusefi/io/serial/RateCounter.java @@ -0,0 +1,55 @@ +package com.rusefi.io.serial; + +import com.rusefi.Timeouts; + +import java.util.LinkedList; + +public class RateCounter { + + private final LinkedList timeStamps = new LinkedList<>(); + + /** + * @return number of events in the last second + */ + public int getCurrentRate() { + return getCurrentRate(System.currentTimeMillis()); + } + + public synchronized int getCurrentRate(long now) { + long threshold = now - Timeouts.SECOND; + + while (!timeStamps.isEmpty() && timeStamps.peekFirst().timestamp < threshold) + timeStamps.removeFirst(); + + int result = 0; + for (Pair pair : timeStamps) + result += pair.value; + return result; + } + + public void add() { + add(System.currentTimeMillis()); + } + + public synchronized void add(long now) { + timeStamps.add(new Pair(now, 1)); + } + + private static class Pair { + private final long timestamp; + private final int value; + + public Pair(long timestamp, int value) { + this.timestamp = timestamp; + this.value = value; + } + + public long getTimestamp() { + return timestamp; + } + + public int getValue() { + return value; + } + } +} diff --git a/java_console/io/src/test/java/com/rusefi/io/serial/RateCounterTest.java b/java_console/io/src/test/java/com/rusefi/io/serial/RateCounterTest.java new file mode 100644 index 0000000000..671cf49768 --- /dev/null +++ b/java_console/io/src/test/java/com/rusefi/io/serial/RateCounterTest.java @@ -0,0 +1,27 @@ +package com.rusefi.io.serial; + +import com.rusefi.Timeouts; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class RateCounterTest { + @Test + public void testRateCalculation() { + + RateCounter rateCounter = new RateCounter(); + + assertEquals(0, rateCounter.getCurrentRate()); + + rateCounter.add(1); + rateCounter.add(1); + rateCounter.add(1); + rateCounter.add(1); + + assertEquals(4, rateCounter.getCurrentRate(0)); + + + assertEquals(0, rateCounter.getCurrentRate(2 * Timeouts.SECOND)); + } +} +