aboutsummaryrefslogtreecommitdiffstats
path: root/vespalib/src/vespa/vespalib/time/time_box.h
blob: ae52b1673a63e5dedbb6bb8cd8cb6f47b09c83d0 (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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#pragma once

#include <chrono>

namespace vespalib {

/**
 * Simple utility for time boxing your activity
 *
 * <pre>
 * Example:
 *
 * TimeBox timebox(5.0);
 * while (timebox.hasTimeLeft()) {
 *   ... do stuff
 *   ... do stuff with timeout(timebox.timeLeft())
 * }
 * </pre>
 **/
class TimeBox
{
private:
    using clock = std::conditional<std::chrono::high_resolution_clock::is_steady,
                                   std::chrono::high_resolution_clock,
                                   std::chrono::steady_clock>::type;

    using seconds = std::chrono::duration<double, std::ratio<1,1>>;

    static inline clock::duration to_internal(double x) {
        return std::chrono::duration_cast<clock::duration>(seconds(x));
    }

    static inline double to_external(clock::duration x) {
        return std::chrono::duration_cast<seconds>(x).count();
    }

    clock::time_point _end_time;
    clock::duration _min_time;

public:
    /**
     * Construct a TimeBox with a given budget from now
     * @param budget amount of time in seconds
     **/
    explicit TimeBox(double budget)
        : _end_time(clock::now() + to_internal(budget)),
          _min_time(to_internal(0))
    {
    }

    /**
     * Construct a TimeBox with a given budget from now
     * @param budget amount of time in seconds
     * @param min_time a minimum to be returned from timeLeft()
     **/
    TimeBox(double budget, double min_time)
        : _end_time(clock::now() + to_internal(budget)),
          _min_time(to_internal(min_time))
    {
    }

    /**
     * @return true if there is time left in the budget
     **/
    bool hasTimeLeft() {
        return clock::now() < _end_time;
    }

    /**
     * Note: Never returns less than min_time even if budget is expired.
     * @return the seconds left before the budget expires
     **/
    double timeLeft() {
        clock::time_point now = clock::now();
        if (now + _min_time < _end_time) {
            return to_external(_end_time - now);
        }
        return to_external(_min_time);
    }
};

} // namespace vespalib