Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package com.yammer.metrics.stats;
  
  
  import static java.lang.Math.exp;

An exponentially-weighted moving average.

See also:
UNIX Load Average Part 1: How It Works
UNIX Load Average Part 2: Not Your Average Average
 
 public class EWMA {
     private static final int INTERVAL = 5;
     private static final double SECONDS_PER_MINUTE = 60.0;
     private static final int ONE_MINUTE = 1;
     private static final int FIVE_MINUTES = 5;
     private static final int FIFTEEN_MINUTES = 15;
     private static final double M1_ALPHA = 1 - exp(- /  / );
     private static final double M5_ALPHA = 1 - exp(- /  / );
     private static final double M15_ALPHA = 1 - exp(- /  / );
 
     private volatile boolean initialized = false;
     private volatile double rate = 0.0;
 
     private final AtomicLong uncounted = new AtomicLong();
     private final double alphainterval;

    
Creates a new EWMA which is equivalent to the UNIX one minute load average and which expects to be ticked every 5 seconds.

Returns:
a one-minute EWMA
 
     public static EWMA oneMinuteEWMA() {
         return new EWMA(.);
     }

    
Creates a new EWMA which is equivalent to the UNIX five minute load average and which expects to be ticked every 5 seconds.

Returns:
a five-minute EWMA
 
     public static EWMA fiveMinuteEWMA() {
         return new EWMA(.);
     }

    
Creates a new EWMA which is equivalent to the UNIX fifteen minute load average and which expects to be ticked every 5 seconds.

Returns:
a fifteen-minute EWMA
 
     public static EWMA fifteenMinuteEWMA() {
         return new EWMA(.);
     }

    
Create a new EWMA with a specific smoothing constant.

Parameters:
alpha the smoothing constant
interval the expected tick interval
intervalUnit the time unit of the tick interval
 
     public EWMA(double alphalong intervalTimeUnit intervalUnit) {
         this. = intervalUnit.toNanos(interval);
         this. = alpha;
     }

    
Update the moving average with a new value.

Parameters:
n the new value
 
     public void update(long n) {
         .addAndGet(n);
     }

    
Mark the passage of time and decay the current rate accordingly.
 
     public void tick() {
         final long count = .getAndSet(0);
         final double instantRate = count / ;
         if () {
              += ( * (instantRate - ));
         } else {
              = instantRate;
              = true;
         }
     }

    
Returns the rate in the given units of time.

Parameters:
rateUnit the unit of time
Returns:
the rate
    public double rate(TimeUnit rateUnit) {
        return  * (doublerateUnit.toNanos(1);
    }
New to GrepCode? Check out our FAQ X