histogram_collector_exponential.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. namespace NMonitoring {
  8. ///////////////////////////////////////////////////////////////////////////
  9. // TExponentialHistogramCollector
  10. ///////////////////////////////////////////////////////////////////////////
  11. class TExponentialHistogramCollector: public IHistogramCollector {
  12. public:
  13. TExponentialHistogramCollector(ui32 bucketsCount, double base, double scale)
  14. : Values_(bucketsCount)
  15. , Base_(base)
  16. , Scale_(scale)
  17. , MinValue_(scale)
  18. , MaxValue_(scale * std::pow(base, bucketsCount - 2))
  19. , LogOfBase_(std::log(base))
  20. {
  21. }
  22. void Collect(double value, ui64 count) noexcept override {
  23. ui32 index = Max<ui32>();
  24. if (value <= MinValue_) {
  25. index = 0;
  26. } else if (value > MaxValue_) {
  27. index = Values_.Size() - 1;
  28. } else {
  29. double logBase = std::log(value / Scale_) / LogOfBase_;
  30. index = static_cast<ui32>(std::ceil(logBase));
  31. }
  32. Values_.Add(index, count);
  33. }
  34. void Reset() noexcept override {
  35. Values_.Reset();
  36. }
  37. IHistogramSnapshotPtr Snapshot() const override {
  38. return new TExponentialHistogramSnapshot(Base_, Scale_, Values_.Copy());
  39. }
  40. private:
  41. TAtomicsArray Values_;
  42. double Base_;
  43. double Scale_;
  44. TBucketBound MinValue_;
  45. TBucketBound MaxValue_;
  46. double LogOfBase_;
  47. };
  48. IHistogramCollectorPtr ExponentialHistogram(
  49. ui32 bucketsCount, double base, double scale)
  50. {
  51. Y_ENSURE(bucketsCount >= 2,
  52. "exponential histogram must contain at least two buckets");
  53. Y_ENSURE(bucketsCount <= HISTOGRAM_MAX_BUCKETS_COUNT,
  54. "buckets count must be <=" << HISTOGRAM_MAX_BUCKETS_COUNT
  55. << ", but got: " << bucketsCount);
  56. Y_ENSURE(base > 1.0, "base must be > 1.0, got: " << base);
  57. Y_ENSURE(scale >= 1.0, "scale must be >= 1.0, got: " << scale);
  58. return MakeHolder<TExponentialHistogramCollector>(bucketsCount, base, scale);
  59. }
  60. }