Skip to content

Commit

Permalink
Prevent NaN values when calculating mean
Browse files Browse the repository at this point in the history
  • Loading branch information
jmartisk committed Feb 19, 2021
1 parent 2b6fcf1 commit 3c8c373
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,9 @@ private void rescale(long now, long next) {
final WeightedSnapshot.WeightedSample sample = values.remove(key);
final WeightedSnapshot.WeightedSample newSample = new WeightedSnapshot.WeightedSample(sample.value,
sample.weight * scalingFactor);
if (Double.compare(newSample.weight, 0) == 0) {
continue;
}
values.put(key * scalingFactor, newSample);
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package io.smallrye.metrics.histogram;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;

import org.eclipse.microprofile.metrics.Histogram;
import org.junit.Assert;
import org.junit.Test;

import io.smallrye.metrics.app.ExponentiallyDecayingReservoir;
import io.smallrye.metrics.app.HistogramImpl;

public class ExponentiallyWeightedReservoirTest {

@Test
public void removeZeroWeightsInSamplesToPreventNaNInMeanValues() {
final TestingClock clock = new TestingClock();
final ExponentiallyDecayingReservoir reservoir = new ExponentiallyDecayingReservoir(1028, 0.015, clock);
Histogram histogram = new HistogramImpl(reservoir);

histogram.update(100);

for (int i = 1; i < 48; i++) {
clock.addHours(1);
Assert.assertThat(reservoir.getSnapshot().getMean(), not(equalTo(Double.NaN)));
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package io.smallrye.metrics.histogram;

import java.util.concurrent.TimeUnit;

import io.smallrye.metrics.app.Clock;

public class TestingClock extends Clock {
private final long initialTicksInNanos;
long ticksInNanos;

public TestingClock(long initialTicksInNanos) {
this.initialTicksInNanos = initialTicksInNanos;
this.ticksInNanos = initialTicksInNanos;
}

public TestingClock() {
this(0L);
}

public synchronized void addNanos(long nanos) {
ticksInNanos += nanos;
}

public synchronized void addSeconds(long seconds) {
ticksInNanos += TimeUnit.SECONDS.toNanos(seconds);
}

public synchronized void addMillis(long millis) {
ticksInNanos += TimeUnit.MILLISECONDS.toNanos(millis);
}

public synchronized void addHours(long hours) {
ticksInNanos += TimeUnit.HOURS.toNanos(hours);
}

@Override
public synchronized long getTick() {
return ticksInNanos;
}

@Override
public synchronized long getTime() {
return TimeUnit.NANOSECONDS.toMillis(ticksInNanos - initialTicksInNanos);
}

}

0 comments on commit 3c8c373

Please sign in to comment.