mon_histogram_helper.h 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #pragma once
  2. #include <library/cpp/monlib/dynamic_counters/counters.h>
  3. #include <util/string/cast.h>
  4. namespace NActors {
  5. namespace NMon {
  6. class THistogramCounterHelper {
  7. public:
  8. THistogramCounterHelper()
  9. : FirstBucketVal(0)
  10. , BucketCount(0)
  11. {
  12. }
  13. THistogramCounterHelper(const THistogramCounterHelper&) = default;
  14. void Init(NMonitoring::TDynamicCounters* group, const TString& baseName, const TString& unit,
  15. ui64 firstBucket, ui64 bucketCnt, bool useSensorLabelName = true)
  16. {
  17. Y_ASSERT(FirstBucketVal == 0);
  18. Y_ASSERT(BucketCount == 0);
  19. FirstBucketVal = firstBucket;
  20. BucketCount = bucketCnt;
  21. BucketsHolder.reserve(BucketCount);
  22. Buckets.reserve(BucketCount);
  23. for (size_t i = 0; i < BucketCount; ++i) {
  24. TString bucketName = GetBucketName(i) + " " + unit;
  25. auto labelName = useSensorLabelName ? "sensor" : "name";
  26. BucketsHolder.push_back(group->GetSubgroup(labelName, baseName)->GetNamedCounter("range", bucketName, true));
  27. Buckets.push_back(BucketsHolder.back().Get());
  28. }
  29. }
  30. void Add(ui64 val) {
  31. Y_ASSERT(FirstBucketVal != 0);
  32. Y_ASSERT(BucketCount != 0);
  33. Y_VERIFY(val <= (1ULL << 63ULL));
  34. size_t ind = 0;
  35. if (val > FirstBucketVal) {
  36. ind = GetValueBitCount((2 * val - 1) / FirstBucketVal) - 1;
  37. if (ind >= BucketCount) {
  38. ind = BucketCount - 1;
  39. }
  40. }
  41. Buckets[ind]->Inc();
  42. }
  43. ui64 GetBucketCount() const {
  44. return BucketCount;
  45. }
  46. ui64 GetBucketValue(size_t index) const {
  47. Y_ASSERT(index < BucketCount);
  48. return Buckets[index]->Val();
  49. }
  50. void SetBucketValue(ui64 index, ui64 value) {
  51. Y_ASSERT(index < BucketCount);
  52. *Buckets[index] = value;
  53. }
  54. private:
  55. TString GetBucketName(size_t ind) const {
  56. Y_ASSERT(FirstBucketVal != 0);
  57. Y_ASSERT(BucketCount != 0);
  58. Y_ASSERT(ind < BucketCount);
  59. if (ind + 1 < BucketCount) {
  60. return ToString<ui64>(FirstBucketVal << ind);
  61. } else {
  62. // Last slot is up to +INF
  63. return "INF";
  64. }
  65. }
  66. private:
  67. ui64 FirstBucketVal;
  68. ui64 BucketCount;
  69. TVector<NMonitoring::TDynamicCounters::TCounterPtr> BucketsHolder;
  70. TVector<NMonitoring::TDeprecatedCounter*> Buckets;
  71. };
  72. }
  73. }