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
17#pragma once
18
19#include <folly/stats/QuantileEstimator.h>
20
21#include <folly/stats/detail/BufferedStat-defs.h>
22
23namespace folly {
24namespace detail {
25
26QuantileEstimates estimatesFromDigest(
27 const TDigest& digest,
28 Range<const double*> quantiles);
29
30} // namespace detail
31
32template <typename ClockT>
33SimpleQuantileEstimator<ClockT>::SimpleQuantileEstimator()
34 : bufferedDigest_(std::chrono::seconds{1}, 1000, 100) {}
35
36template <typename ClockT>
37QuantileEstimates SimpleQuantileEstimator<ClockT>::estimateQuantiles(
38 Range<const double*> quantiles,
39 TimePoint now) {
40 auto digest = bufferedDigest_.get(now);
41 return detail::estimatesFromDigest(digest, quantiles);
42}
43
44template <typename ClockT>
45void SimpleQuantileEstimator<ClockT>::addValue(double value, TimePoint now) {
46 bufferedDigest_.append(value, now);
47}
48
49template <typename ClockT>
50SlidingWindowQuantileEstimator<ClockT>::SlidingWindowQuantileEstimator(
51 std::chrono::seconds windowDuration,
52 size_t nWindows)
53 : bufferedSlidingWindow_(nWindows, windowDuration, 1000, 100) {}
54
55template <typename ClockT>
56QuantileEstimates SlidingWindowQuantileEstimator<ClockT>::estimateQuantiles(
57 Range<const double*> quantiles,
58 TimePoint now) {
59 auto digests = bufferedSlidingWindow_.get(now);
60 auto digest = TDigest::merge(digests);
61 return detail::estimatesFromDigest(digest, quantiles);
62}
63
64template <typename ClockT>
65void SlidingWindowQuantileEstimator<ClockT>::addValue(
66 double value,
67 TimePoint now) {
68 bufferedSlidingWindow_.append(value, now);
69}
70
71} // namespace folly
72