Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2012
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.62 KB | None | 0 0
  1. private static class RunningAvg {
  2.       private final long[] slots;
  3.       private int          offset;
  4.       private long     sum;
  5.  
  6.       public RunningAvg(int slotCount) {
  7.          this.slots = new long[slotCount];
  8.          this.offset = 0;
  9.       }
  10.  
  11.       public void add(long value) {
  12.           // add new value and remove old value (last in array) from sum
  13.           sum = value - slots[(offset+1) % slots.length];
  14.           slots[offset++ % slots.length] = value;
  15.       }
  16.  
  17.       public long avg() {
  18.          int sampleCount = Math.min(this.offset, this.slots.length);
  19.          return sum / sampleCount;
  20.       }
  21.    }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement