aboutsummaryrefslogtreecommitdiffstats
path: root/service-monitor/src/main/java/com/yahoo/vespa/service/model/LatencyMeasurement.java
blob: 93318a8e34880b1fdb46d7a279e387576e93d5a2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

package com.yahoo.vespa.service.model;

import com.yahoo.jdisc.Timer;

import java.util.function.Consumer;

public class LatencyMeasurement implements AutoCloseable {
    private final Timer timer;
    private Consumer<Double> elapsedSecondsConsumer;
    private long startMillis;

    LatencyMeasurement(Timer timer, Consumer<Double> elapsedSecondsConsumer) {
        this.timer = timer;
        this.elapsedSecondsConsumer = elapsedSecondsConsumer;
    }

    LatencyMeasurement start() {
        startMillis = timer.currentTimeMillis();
        return this;
    }

    @Override
    public void close() {
        if (elapsedSecondsConsumer != null) {
            double elapsedSeconds = forceNonNegative(timer.currentTimeMillis() - startMillis) / 1000;
            elapsedSecondsConsumer.accept(elapsedSeconds);
            elapsedSecondsConsumer = null;
        }
    }

    private static double forceNonNegative(double d) {
        return d > 0 ? d : 0;
    }
}