Created
July 15, 2020 19:32
-
-
Save gordinmitya/0ee8cb72705de3a12109ddaa07888d02 to your computer and use it in GitHub Desktop.
Moving average for performance measurements in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MovingAvg { | |
public final long[] measurements; | |
public final int size; | |
private int pointer = 0; | |
public MovingAvg(int size) { | |
measurements = new long[size]; | |
this.size = size; | |
} | |
public void add(long time) { | |
measurements[pointer++ % size] = time; | |
} | |
public int count() { | |
return Math.min(pointer, size); | |
} | |
public double avg() { | |
if (pointer == 0) | |
throw new RuntimeException("no measurements"); | |
double sum = 0; | |
int count = count(); | |
for (int i = 0; i < count; ++i) | |
sum += measurements[i]; | |
return sum / count; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment