histogram_snapshot.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #include "histogram_snapshot.h"
  2. #include <util/stream/output.h>
  3. #include <iostream>
  4. namespace NMonitoring {
  5. IHistogramSnapshotPtr ExplicitHistogramSnapshot(TConstArrayRef<TBucketBound> bounds, TConstArrayRef<TBucketValue> values, bool shrinkBuckets) {
  6. Y_ENSURE(bounds.size() == values.size(),
  7. "mismatched sizes: bounds(" << bounds.size() <<
  8. ") != buckets(" << values.size() << ')');
  9. size_t requiredSize = shrinkBuckets ? std::min(bounds.size(), static_cast<size_t>(HISTOGRAM_MAX_BUCKETS_COUNT)) : bounds.size();
  10. auto snapshot = TExplicitHistogramSnapshot::New(requiredSize);
  11. if (requiredSize < bounds.size()) {
  12. auto remains = bounds.size() % requiredSize;
  13. auto divided = bounds.size() / requiredSize;
  14. size_t idx{bounds.size()};
  15. for (size_t i = requiredSize; i > 0; --i) {
  16. Y_ENSURE(idx > 0);
  17. (*snapshot)[i - 1].first = bounds[idx - 1];
  18. (*snapshot)[i - 1].second = 0;
  19. auto repeat = divided;
  20. if (remains > 0) {
  21. ++repeat;
  22. --remains;
  23. }
  24. for (; repeat > 0; --repeat) {
  25. Y_ENSURE(idx > 0);
  26. (*snapshot)[i - 1].second += values[idx - 1];
  27. --idx;
  28. }
  29. }
  30. } else {
  31. for (size_t i = 0; i != bounds.size(); ++i) {
  32. (*snapshot)[i].first = bounds[i];
  33. (*snapshot)[i].second = values[i];
  34. }
  35. }
  36. return snapshot;
  37. }
  38. } // namespace NMonitoring
  39. namespace {
  40. template <typename TStream>
  41. auto& Output(TStream& os, const NMonitoring::IHistogramSnapshot& hist) {
  42. os << TStringBuf("{");
  43. ui32 i = 0;
  44. ui32 count = hist.Count();
  45. if (count > 0) {
  46. for (; i < count - 1; ++i) {
  47. os << hist.UpperBound(i) << TStringBuf(": ") << hist.Value(i);
  48. os << TStringBuf(", ");
  49. }
  50. if (hist.UpperBound(i) == Max<NMonitoring::TBucketBound>()) {
  51. os << TStringBuf("inf: ") << hist.Value(i);
  52. } else {
  53. os << hist.UpperBound(i) << TStringBuf(": ") << hist.Value(i);
  54. }
  55. }
  56. os << TStringBuf("}");
  57. return os;
  58. }
  59. } // namespace
  60. std::ostream& operator<<(std::ostream& os, const NMonitoring::IHistogramSnapshot& hist) {
  61. return Output(os, hist);
  62. }
  63. template <>
  64. void Out<NMonitoring::IHistogramSnapshot>(IOutputStream& os, const NMonitoring::IHistogramSnapshot& hist) {
  65. Output(os, hist);
  66. }