Skip to content

Instantly share code, notes, and snippets.

@gordinmitya
Created July 15, 2020 19:32
Show Gist options
  • Save gordinmitya/0ee8cb72705de3a12109ddaa07888d02 to your computer and use it in GitHub Desktop.
Save gordinmitya/0ee8cb72705de3a12109ddaa07888d02 to your computer and use it in GitHub Desktop.
Moving average for performance measurements in Java
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