aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/messagebus/duration_histogram.cpp
blob: 32a0001d41492cbff61c39664c9c9d9ed70ac657 (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
#include "duration_histogram.h"

#include <util/generic/singleton.h>
#include <util/stream/str.h>

namespace {
    ui64 SecondsRound(TDuration d) {
        if (d.MilliSeconds() % 1000 >= 500) {
            return d.Seconds() + 1;
        } else {
            return d.Seconds();
        }
    }

    ui64 MilliSecondsRound(TDuration d) {
        if (d.MicroSeconds() % 1000 >= 500) {
            return d.MilliSeconds() + 1;
        } else {
            return d.MilliSeconds();
        }
    }

    ui64 MinutesRound(TDuration d) {
        if (d.Seconds() % 60 >= 30) {
            return d.Minutes() + 1;
        } else {
            return d.Minutes();
        }
    }

}

namespace {
    struct TMarks {
        std::array<TDuration, TDurationHistogram::Buckets> Marks;

        TMarks() {
            Marks[0] = TDuration::Zero();
            for (unsigned i = 1; i < TDurationHistogram::Buckets; ++i) {
                if (i >= TDurationHistogram::SecondBoundary) {
                    Marks[i] = TDuration::Seconds(1) * (1 << (i - TDurationHistogram::SecondBoundary));
                } else {
                    Marks[i] = TDuration::Seconds(1) / (1 << (TDurationHistogram::SecondBoundary - i));
                }
            }
        }
    };
}

TString TDurationHistogram::LabelBefore(unsigned i) {
    Y_VERIFY(i < Buckets);

    TDuration d = Singleton<TMarks>()->Marks[i];

    TStringStream ss;
    if (d == TDuration::Zero()) {
        ss << "0";
    } else if (d < TDuration::Seconds(1)) {
        ss << MilliSecondsRound(d) << "ms";
    } else if (d < TDuration::Minutes(1)) {
        ss << SecondsRound(d) << "s";
    } else {
        ss << MinutesRound(d) << "m";
    }
    return ss.Str();
}

TString TDurationHistogram::PrintToString() const {
    TStringStream ss;
    for (auto time : Times) {
        ss << time << "\n";
    }
    return ss.Str();
}