aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/messagebus/duration_histogram.h
blob: ed060b0101a6dd7b708ded612f9ec83d0552573d (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
#pragma once

#include <util/datetime/base.h>
#include <util/generic/bitops.h>
#include <util/generic/string.h>

#include <array>

struct TDurationHistogram {
    static const unsigned Buckets = 20;
    std::array<ui64, Buckets> Times;

    static const unsigned SecondBoundary = 11;

    TDurationHistogram() {
        Times.fill(0);
    }

    static unsigned BucketFor(TDuration d) {
        ui64 units = d.MicroSeconds() * (1 << SecondBoundary) / 1000000;
        if (units == 0) {
            return 0;
        }
        unsigned bucket = GetValueBitCount(units) - 1;
        if (bucket >= Buckets) {
            bucket = Buckets - 1;
        }
        return bucket;
    }

    void AddTime(TDuration d) {
        Times[BucketFor(d)] += 1;
    }

    TDurationHistogram& operator+=(const TDurationHistogram& that) {
        for (unsigned i = 0; i < Times.size(); ++i) {
            Times[i] += that.Times[i];
        }
        return *this;
    }

    static TString LabelBefore(unsigned i);

    TString PrintToString() const;
};