QuantileEstimator.h 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. * Copyright 2018-present Facebook, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #pragma once
  17. #include <folly/stats/TDigest.h>
  18. #include <folly/stats/detail/BufferedStat.h>
  19. namespace folly {
  20. struct QuantileEstimates {
  21. public:
  22. double sum;
  23. double count;
  24. // vector of {quantile, value}
  25. std::vector<std::pair<double, double>> quantiles;
  26. };
  27. /*
  28. * A QuantileEstimator that buffers writes for 1 second.
  29. */
  30. template <typename ClockT = std::chrono::steady_clock>
  31. class SimpleQuantileEstimator {
  32. public:
  33. using TimePoint = typename ClockT::time_point;
  34. SimpleQuantileEstimator();
  35. QuantileEstimates estimateQuantiles(
  36. Range<const double*> quantiles,
  37. TimePoint now = ClockT::now());
  38. void addValue(double value, TimePoint now = ClockT::now());
  39. /// Flush buffered values
  40. void flush() {
  41. bufferedDigest_.flush();
  42. }
  43. private:
  44. detail::BufferedDigest<TDigest, ClockT> bufferedDigest_;
  45. };
  46. /*
  47. * A QuantileEstimator that keeps values for nWindows * windowDuration (see
  48. * constructor). Values are buffered for windowDuration.
  49. */
  50. template <typename ClockT = std::chrono::steady_clock>
  51. class SlidingWindowQuantileEstimator {
  52. public:
  53. using TimePoint = typename ClockT::time_point;
  54. SlidingWindowQuantileEstimator(
  55. std::chrono::seconds windowDuration,
  56. size_t nWindows = 60);
  57. QuantileEstimates estimateQuantiles(
  58. Range<const double*> quantiles,
  59. TimePoint now = ClockT::now());
  60. void addValue(double value, TimePoint now = ClockT::now());
  61. /// Flush buffered values
  62. void flush() {
  63. bufferedSlidingWindow_.flush();
  64. }
  65. private:
  66. detail::BufferedSlidingWindow<TDigest, ClockT> bufferedSlidingWindow_;
  67. };
  68. extern template class SimpleQuantileEstimator<std::chrono::steady_clock>;
  69. extern template class SlidingWindowQuantileEstimator<std::chrono::steady_clock>;
  70. } // namespace folly