aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/messagebus/duration_histogram.h
blob: 6b2f6a9bda54000c12f73308d877d465c9be8838 (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; 
};