need more statistics

This commit is contained in:
rusefi 2020-07-31 09:03:23 -04:00
parent 4887faab14
commit 7889528876
2 changed files with 82 additions and 0 deletions

View File

@ -0,0 +1,55 @@
package com.rusefi.io.serial;
import com.rusefi.Timeouts;
import java.util.LinkedList;
public class RateCounter {
private final LinkedList<Pair> 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;
}
}
}

View File

@ -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));
}
}