Created
May 5, 2016 07:27
-
-
Save coderodde/81dbf852853e45f616e088464e7dfe66 to your computer and use it in GitHub Desktop.
This file contains 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
import java.math.BigDecimal; | |
import java.math.RoundingMode; | |
import java.util.ArrayDeque; | |
import java.util.Queue; | |
import java.util.Random; | |
public class MovingAverageV2 { | |
private final Queue<BigDecimal> window = new ArrayDeque<>(); | |
private final int period; | |
private BigDecimal sum = BigDecimal.ZERO; | |
public MovingAverageV2(int period) { | |
this.period = period; | |
} | |
public void add(BigDecimal num) { | |
sum = sum.add(num); | |
window.add(num); | |
if (window.size() > period) { | |
sum = sum.subtract(window.remove()); | |
} | |
} | |
public BigDecimal getAverage() { | |
if (window.isEmpty()) { | |
return BigDecimal.ZERO; | |
} | |
BigDecimal divisor = BigDecimal.valueOf(window.size()); | |
return sum.divide(divisor, 2, RoundingMode.HALF_UP); | |
} | |
public static void main(final String[] args) { | |
final Random random = new Random(); | |
warmup(random); | |
final MovingAverage ma = new MovingAverage(10); | |
final MovingAverageV2 mav2 = new MovingAverageV2(10); | |
long startTime = System.nanoTime(); | |
for (int i = 0; i < 10_000_000; ++i) { | |
ma.add(BigDecimal.valueOf(random.nextLong())); | |
} | |
long endTime = System.nanoTime(); | |
System.out.printf("MovingAverage in %.1f milliseconds.\n", | |
(endTime - startTime) / 1e6); | |
startTime = System.nanoTime(); | |
for (int i = 0; i < 10_000_000; ++i) { | |
mav2.add(BigDecimal.valueOf(random.nextLong())); | |
} | |
endTime = System.nanoTime(); | |
System.out.printf("MovingAverageV2 in %.1f milliseconds.\n", | |
(endTime - startTime) / 1e6); | |
} | |
private static void warmup(final Random random) { | |
final MovingAverage ma = new MovingAverage(10); | |
final MovingAverageV2 mav2 = new MovingAverageV2(10); | |
for (int i = 0; i < 100; ++i) { | |
for (int j = 0; j < 10_000; ++j) { | |
final BigDecimal value = BigDecimal.valueOf(random.nextLong()); | |
ma.add(value); | |
mav2.add(value); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment