INT-3653: Fix Mean Calculations

JIRA: https://jira.spring.io/browse/INT-3653

After moving to nanosecond precision, the mean calculations were incorrect.

Add test cases to verify correctness.
This commit is contained in:
Gary Russell
2015-02-20 15:53:12 -05:00
committed by Artem Bilan
parent 45eaadd6ac
commit 2214b48aa0
5 changed files with 55 additions and 3 deletions

View File

@@ -124,7 +124,7 @@ public class ExponentialMovingAverageRate {
}
long delta = System.nanoTime() - t0;
double value = delta > 0 ? delta / period : 0;
return count / (count / rates.getMeanNanos() + value);
return count / (count / rates.getMean() + value);
}
/**

View File

@@ -95,7 +95,7 @@ public class ExponentialMovingAverageRatio {
t0 = t;
sum = alpha * sum + value;
weight = alpha * weight + 1;
cumulative.appendNanos(sum / weight);
cumulative.append(sum / weight);
}
/**
@@ -130,7 +130,7 @@ public class ExponentialMovingAverageRatio {
}
long t = System.nanoTime();
double alpha = Math.exp((t0 - t) / 1000000. * lapse);
return alpha * cumulative.getMeanNanos() + 1 - alpha;
return alpha * cumulative.getMean() + 1 - alpha;
}
/**

View File

@@ -22,6 +22,7 @@ import org.junit.Ignore;
import org.junit.Test;
import org.springframework.integration.test.util.TestUtils;
import org.springframework.util.StopWatch;
/**
* @author Dave Syer
@@ -126,4 +127,18 @@ public class ExponentialMovingAverageRateTests {
assertEquals(0, history.getMax(), 0.01);
}
@Test
public void testRate() {
ExponentialMovingAverageRate rate = new ExponentialMovingAverageRate(1, 60, 10);
int count = 1000000;
StopWatch watch = new StopWatch();
watch.start();
for (int i = 0; i < count; i++) {
rate.increment();
}
watch.stop();
double calculatedRate = count / (double) watch.getTotalTimeMillis() * 1000;
assertEquals(calculatedRate, rate.getMean(), 2000000);
}
}

View File

@@ -130,4 +130,19 @@ public class ExponentialMovingAverageRatioTests {
return sum / count;
}
@Test
public void testRatio() {
ExponentialMovingAverageRatio ratio = new ExponentialMovingAverageRatio(60, 10);
for (int i = 0; i < 10000; i++) {
if (i % 10 == 0) {
ratio.failure();
}
else {
ratio.success();
}
}
assertEquals(0.9, ratio.getMax(), 0.01);
assertEquals(0.9, ratio.getMean(), 0.01);
}
}

View File

@@ -65,4 +65,26 @@ public class ExponentialMovingAverageTests {
assertEquals(String.format("[N=%d, min=%f, max=%f, mean=%f, sigma=%f]", 0, 0d, 0d, 0d, 0d), history.toString());
}
@Test
public void testAv() throws Exception {
ExponentialMovingAverage av = new ExponentialMovingAverage(10);
for (int i = 0; i < 10000; i++) {
switch (i % 3) {
case 0:
av.appendNanos(20000);
break;
case 1:
av.appendNanos(30000);
break;
case 2:
av.appendNanos(40000);
break;
}
}
assertEquals(0.04, av.getMax(), 0.001);
assertEquals(0.02, av.getMin(), 0.001);
assertEquals(0.03, av.getMean(), 0.001);
}
}