histogram_collector_linear.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #include "histogram_collector.h"
  2. #include "atomics_array.h"
  3. #include <util/generic/algorithm.h>
  4. #include <util/generic/vector.h>
  5. #include <util/generic/yexception.h>
  6. #include <util/generic/ylimits.h>
  7. #include <cmath>
  8. namespace NMonitoring {
  9. ///////////////////////////////////////////////////////////////////////////
  10. // TLinearHistogramCollector
  11. ///////////////////////////////////////////////////////////////////////////
  12. class TLinearHistogramCollector: public IHistogramCollector {
  13. public:
  14. TLinearHistogramCollector(
  15. ui32 bucketsCount, TBucketBound startValue, TBucketBound bucketWidth)
  16. : Values_(bucketsCount)
  17. , StartValue_(startValue)
  18. , BucketWidth_(bucketWidth)
  19. , MaxValue_(startValue + bucketWidth * (bucketsCount - 2))
  20. {
  21. }
  22. void Collect(double value, ui64 count) override {
  23. ui32 index = Max<ui32>();
  24. if (value <= StartValue_) {
  25. index = 0;
  26. } else if (value > MaxValue_) {
  27. index = Values_.Size() - 1;
  28. } else {
  29. double buckets = (value - StartValue_) / BucketWidth_;
  30. index = static_cast<ui32>(std::ceil(buckets));
  31. }
  32. Values_.Add(index, count);
  33. }
  34. void Reset() override {
  35. Values_.Reset();
  36. }
  37. IHistogramSnapshotPtr Snapshot() const override {
  38. return new TLinearHistogramSnapshot(
  39. StartValue_, BucketWidth_, Values_.Copy());
  40. }
  41. private:
  42. TAtomicsArray Values_;
  43. TBucketBound StartValue_;
  44. double BucketWidth_;
  45. TBucketBound MaxValue_;
  46. };
  47. IHistogramCollectorPtr LinearHistogram(
  48. ui32 bucketsCount, TBucketBound startValue, TBucketBound bucketWidth)
  49. {
  50. Y_ENSURE(bucketsCount >= 2,
  51. "linear histogram must contain at least two buckets");
  52. Y_ENSURE(bucketsCount <= HISTOGRAM_MAX_BUCKETS_COUNT,
  53. "buckets count must be <=" << HISTOGRAM_MAX_BUCKETS_COUNT
  54. << ", but got: " << bucketsCount);
  55. Y_ENSURE(bucketWidth >= 1, "bucketWidth must be >= 1, got: " << bucketWidth);
  56. return MakeHolder<TLinearHistogramCollector>(bucketsCount, startValue, bucketWidth);
  57. }
  58. }