aboutsummaryrefslogtreecommitdiffstats
path: root/metrics/src/vespa/metrics/metrictimer.h
blob: e2506c96bf6d43ef71f517fb61e223557a95d858 (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
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
/**
 * @class MetricTimer
 * @ingruop metrics
 *
 * @brief Used to add time values to metrics.
 */

#pragma once

#include "valuemetric.h"
#include <chrono>

namespace metrics {

class MetricTimer {
public:
    MetricTimer();

    /**
     * Adds ms passed since this timer was constructed to given value metric.
     * Returns that value as well.
     *
     * Uses a steady (monotonic) clock internally so value should never
     * underflow or be affected by system clock changes.
     */
    template<typename AvgVal, typename TotVal, bool SumOnAdd>
    AvgVal stop(ValueMetric<AvgVal, TotVal, SumOnAdd>& metric) const {
        const auto delta = std::chrono::steady_clock::now() - _startTime;
        using ToDuration = std::chrono::duration<AvgVal, std::milli>;
        const auto deltaMs(std::chrono::duration_cast<ToDuration>(delta).count());
        metric.addValue(deltaMs);
        return deltaMs;
    }

private:
    std::chrono::steady_clock::time_point _startTime;
};

} // metrics