aboutsummaryrefslogtreecommitdiffstats
path: root/container-search/src/main/java/com/yahoo/search/dispatch/RequestDuration.java
blob: 6b134dc23a69f31d29d5d4d26c32ab6f22b5c35a (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
37
38
39
40
41
42
43
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.dispatch;

import java.time.Duration;
import java.time.Instant;

/**
 * Contains start and end time. Exposes a duration, and lets you measure the time difference between 2 requests.
 * It does use System.nanoTime to get a steady clock.
 *
 * @author baldersheim
 */
class RequestDuration {
    private final long startTime;
    private long endTime;
    RequestDuration() {
        this(System.nanoTime());
    }
    private RequestDuration(long startTime) {
        this.startTime = startTime;
    }

    RequestDuration complete() {
        endTime = System.nanoTime();
        return this;
    }
    private RequestDuration complete(long duration) {
        endTime = startTime + duration;
        return this;
    }
    Duration duration() {
        return Duration.ofNanos(endTime - startTime);
    }
    Duration difference(RequestDuration prev) {
        return Duration.ofNanos(Math.abs(endTime - prev.endTime));
    }
    static RequestDuration of(Duration duration) {
        return new RequestDuration().complete(duration.toNanos());
    }
    static RequestDuration of(Instant sinceEpoch, Duration duration) {
        return new RequestDuration(sinceEpoch.toEpochMilli()*1_000_000).complete(duration.toNanos());
    }
}