Record experiment results with a timer instead of a counter.

This commit is contained in:
Jon Chambers
2020-06-09 16:35:16 -04:00
committed by Jon Chambers
parent d980b8cfdc
commit 0713da7393
2 changed files with 32 additions and 21 deletions

View File

@@ -9,13 +9,14 @@ import io.micrometer.core.instrument.Tag;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.TimeUnit;
/**
* An experiment compares the results of two operations and records metrics to assess how frequently they match.
*/
public class Experiment {
private final String counterName;
private final String timerName;
private final MeterRegistry meterRegistry;
static final String OUTCOME_TAG = "outcome";
@@ -35,23 +36,29 @@ public class Experiment {
throw new IllegalArgumentException("Experiments must have a name");
}
this.counterName = MetricRegistry.name(getClass(), names);
this.timerName = MetricRegistry.name(getClass(), names);
this.meterRegistry = meterRegistry;
}
public <T> void compareResult(final T expected, final CompletionStage<T> experimentStage) {
// We're assuming that we get the experiment completion stage as soon as possible after it's started, but this
// start time will inescapably have some "wiggle" to it.
final long start = System.nanoTime();
experimentStage.whenComplete((actual, cause) -> {
final long duration = System.nanoTime() - start;
if (cause != null) {
meterRegistry.counter(counterName,
meterRegistry.timer(timerName,
List.of(Tag.of(OUTCOME_TAG, ERROR_OUTCOME), Tag.of(CAUSE_TAG, cause.getClass().getSimpleName())))
.increment();
.record(duration, TimeUnit.NANOSECONDS);
} else {
final boolean shouldIgnore = actual == null && expected != null;
if (!shouldIgnore) {
meterRegistry.counter(counterName,
meterRegistry.timer(timerName,
List.of(Tag.of(OUTCOME_TAG, Objects.equals(expected, actual) ? MATCH_OUTCOME : MISMATCH_OUTCOME)))
.increment();
.record(duration, TimeUnit.NANOSECONDS);
}
}
});