xrpld
Loading...
Searching...
No Matches
Histogram.h
1#pragma once
2
3#include <algorithm>
4#include <cassert>
5#include <chrono>
6#include <cmath>
7#include <map>
8
9namespace xrpl::test::csf {
10
22template <class T, class Compare = std::less<T>>
24{
25 // TODO: Consider logarithmic bins around expected median if this becomes
26 // unscalable
29
30public:
32 void
33 insert(T const& s)
34 {
35 ++counts_[s];
36 ++samples_;
37 }
38
40 [[nodiscard]] std::size_t
41 size() const
42 {
43 return samples_;
44 }
45
47 [[nodiscard]] std::size_t
48 numBins() const
49 {
50 return counts_.size();
51 }
52
54 [[nodiscard]] T
55 minValue() const
56 {
57 return counts_.empty() ? T{} : counts_.begin()->first;
58 }
59
61 [[nodiscard]] T
62 maxValue() const
63 {
64 return counts_.empty() ? T{} : counts_.rbegin()->first;
65 }
66
68 [[nodiscard]] T
69 avg() const
70 {
71 T tmp{};
72 if (samples_ == 0)
73 return tmp;
74 // Since counts are sorted, shouldn't need to worry much about numerical
75 // error
76 for (auto const& [bin, count] : counts_)
77 {
78 tmp += bin * count;
79 }
80 return tmp / samples_;
81 }
82
89 [[nodiscard]] T
90 percentile(float p) const
91 {
92 assert(p >= 0 && p <= 1);
93 std::size_t const pos = std::round(p * samples_);
94
95 if (counts_.empty())
96 return T{};
97
98 auto it = counts_.begin();
99 std::size_t cumsum = it->second;
100 while (it != counts_.end() && cumsum < pos)
101 {
102 ++it;
103 cumsum += it->second;
104 }
105 return it->first;
106 }
107};
108
109} // namespace xrpl::test::csf
Basic histogram.
Definition Histogram.h:24
std::size_t numBins() const
The number of distinct samples (bins).
Definition Histogram.h:48
T percentile(float p) const
Calculate the given percentile of the distribution.
Definition Histogram.h:90
T maxValue() const
Maximum observed value.
Definition Histogram.h:62
T avg() const
Histogram average.
Definition Histogram.h:69
std::map< SimTime::duration, std::size_t, std::less< SimTime::duration > > counts_
Definition Histogram.h:27
T minValue() const
Minimum observed value.
Definition Histogram.h:55
std::size_t size() const
The number of samples.
Definition Histogram.h:41
void insert(T const &s)
Insert an sample.
Definition Histogram.h:33
T round(T... args)