2 * Copyright 2017 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
20 #include <folly/stats/Histogram.h>
21 #include <folly/stats/MultiLevelTimeSeries.h>
26 * TimeseriesHistogram tracks data distributions as they change over time.
28 * Specifically, it is a bucketed histogram with different value ranges assigned
29 * to each bucket. Within each bucket is a MultiLevelTimeSeries from
30 * 'folly/stats/MultiLevelTimeSeries.h'. This means that each bucket contains a
31 * different set of data for different historical time periods, and one can
32 * query data distributions over different trailing time windows.
34 * For example, this can answer questions: "What is the data distribution over
35 * the last minute? Over the last 10 minutes? Since I last cleared this
38 * The class can also estimate percentiles and answer questions like: "What was
39 * the 99th percentile data value over the last 10 minutes?"
41 * Note: that depending on the size of your buckets and the smoothness
42 * of your data distribution, the estimate may be way off from the actual
43 * value. In particular, if the given percentile falls outside of the bucket
44 * range (i.e. your buckets range in 0 - 100,000 but the 99th percentile is
45 * around 115,000) this estimate may be very wrong.
47 * The memory usage for a typical histogram is roughly 3k * (# of buckets). All
48 * insertion operations are amortized O(1), and all queries are O(# of buckets).
52 class CT = LegacyStatsClock<std::chrono::seconds>,
53 class C = folly::MultiLevelTimeSeries<T, CT>>
54 class TimeseriesHistogram {
56 // NOTE: T must be equivalent to _signed_ numeric type for our math.
57 static_assert(std::numeric_limits<T>::is_signed, "");
60 // Values to be inserted into container
62 // The container type we use internally for each bucket
63 using ContainerType = C;
64 // Clock, duration, and time point types
66 using Duration = typename Clock::duration;
67 using TimePoint = typename Clock::time_point;
70 * Create a TimeSeries histogram and initialize the bucketing and levels.
72 * The buckets are created by chopping the range [min, max) into pieces
73 * of size bucketSize, with the last bucket being potentially shorter. Two
74 * additional buckets are always created -- the "under" bucket for the range
75 * (-inf, min) and the "over" bucket for the range [max, +inf).
77 * @param bucketSize the width of each bucket
78 * @param min the smallest value for the bucket range.
79 * @param max the largest value for the bucket range
80 * @param defaultContainer a pre-initialized timeseries with the desired
81 * number of levels and their durations.
83 TimeseriesHistogram(ValueType bucketSize, ValueType min, ValueType max,
84 const ContainerType& defaultContainer);
86 /* Return the bucket size of each bucket in the histogram. */
87 ValueType getBucketSize() const { return buckets_.getBucketSize(); }
89 /* Return the min value at which bucketing begins. */
90 ValueType getMin() const { return buckets_.getMin(); }
92 /* Return the max value at which bucketing ends. */
93 ValueType getMax() const { return buckets_.getMax(); }
95 /* Return the number of levels of the Timeseries object in each bucket */
96 size_t getNumLevels() const {
97 return buckets_.getByIndex(0).numLevels();
100 /* Return the number of buckets */
101 size_t getNumBuckets() const {
102 return buckets_.getNumBuckets();
106 * Return the threshold of the bucket for the given index in range
107 * [0..numBuckets). The bucket will have range [thresh, thresh + bucketSize)
108 * or [thresh, max), whichever is shorter.
110 ValueType getBucketMin(size_t bucketIdx) const {
111 return buckets_.getBucketMin(bucketIdx);
114 /* Return the actual timeseries in the given bucket (for reading only!) */
115 const ContainerType& getBucket(size_t bucketIdx) const {
116 return buckets_.getByIndex(bucketIdx);
119 /* Total count of values at the given timeseries level (all buckets). */
120 uint64_t count(size_t level) const {
122 for (size_t b = 0; b < buckets_.getNumBuckets(); ++b) {
123 total += buckets_.getByIndex(b).count(level);
128 /* Total count of values added during the given interval (all buckets). */
129 uint64_t count(TimePoint start, TimePoint end) const {
131 for (size_t b = 0; b < buckets_.getNumBuckets(); ++b) {
132 total += buckets_.getByIndex(b).count(start, end);
137 /* Total sum of values at the given timeseries level (all buckets). */
138 ValueType sum(size_t level) const {
139 ValueType total = ValueType();
140 for (size_t b = 0; b < buckets_.getNumBuckets(); ++b) {
141 total += buckets_.getByIndex(b).sum(level);
146 /* Total sum of values added during the given interval (all buckets). */
147 ValueType sum(TimePoint start, TimePoint end) const {
148 ValueType total = ValueType();
149 for (size_t b = 0; b < buckets_.getNumBuckets(); ++b) {
150 total += buckets_.getByIndex(b).sum(start, end);
155 /* Average of values at the given timeseries level (all buckets). */
156 template <typename ReturnType = double>
157 ReturnType avg(size_t level) const {
158 auto total = ValueType();
159 uint64_t nsamples = 0;
160 computeAvgData(&total, &nsamples, level);
161 return folly::detail::avgHelper<ReturnType>(total, nsamples);
164 /* Average of values added during the given interval (all buckets). */
165 template <typename ReturnType = double>
166 ReturnType avg(TimePoint start, TimePoint end) const {
167 auto total = ValueType();
168 uint64_t nsamples = 0;
169 computeAvgData(&total, &nsamples, start, end);
170 return folly::detail::avgHelper<ReturnType>(total, nsamples);
174 * Rate at the given timeseries level (all buckets).
175 * This is the sum of all values divided by the time interval (in seconds).
177 template <typename ReturnType = double>
178 ReturnType rate(size_t level) const {
179 auto total = ValueType();
181 computeRateData(&total, &elapsed, level);
182 return folly::detail::rateHelper<ReturnType, Duration, Duration>(
187 * Rate for the given interval (all buckets).
188 * This is the sum of all values divided by the time interval (in seconds).
190 template <typename ReturnType = double>
191 ReturnType rate(TimePoint start, TimePoint end) const {
192 auto total = ValueType();
194 computeRateData(&total, &elapsed, start, end);
195 return folly::detail::rateHelper<ReturnType, Duration, Duration>(
200 * Update every underlying timeseries object with the given timestamp. You
201 * must call this directly before querying to ensure that the data in all
202 * buckets is decayed properly.
204 void update(TimePoint now);
206 /* clear all the data from the histogram. */
209 /* Add a value into the histogram with timestamp 'now' */
210 void addValue(TimePoint now, const ValueType& value);
211 /* Add a value the given number of times with timestamp 'now' */
212 void addValue(TimePoint now, const ValueType& value, uint64_t times);
215 * Add all of the values from the specified histogram.
217 * All of the values will be added to the current time-slot.
219 * One use of this is for thread-local caching of frequently updated
220 * histogram data. For example, each thread can store a thread-local
221 * Histogram that is updated frequently, and only add it to the global
222 * TimeseriesHistogram once a second.
224 void addValues(TimePoint now, const folly::Histogram<ValueType>& values);
227 * Return an estimate of the value at the given percentile in the histogram
228 * in the given timeseries level. The percentile is estimated as follows:
230 * - We retrieve a count of the values in each bucket (at the given level)
231 * - We determine via the counts which bucket the given percentile falls in.
232 * - We assume the average value in the bucket is also its median
233 * - We then linearly interpolate within the bucket, by assuming that the
234 * distribution is uniform in the two value ranges [left, median) and
235 * [median, right) where [left, right) is the bucket value range.
238 * - If the histogram is empty, this always returns ValueType(), usually 0.
239 * - For the 'under' and 'over' special buckets, their range is unbounded
240 * on one side. In order for the interpolation to work, we assume that
241 * the average value in the bucket is equidistant from the two edges of
242 * the bucket. In other words, we assume that the distance between the
243 * average and the known bound is equal to the distance between the average
244 * and the unknown bound.
246 ValueType getPercentileEstimate(double pct, size_t level) const;
248 * Return an estimate of the value at the given percentile in the histogram
249 * in the given historical interval. Please see the documentation for
250 * getPercentileEstimate(double pct, size_t level) for the explanation of the
251 * estimation algorithm.
253 ValueType getPercentileEstimate(double pct, TimePoint start, TimePoint end)
257 * Return the bucket index that the given percentile falls into (in the
258 * given timeseries level). This index can then be used to retrieve either
259 * the bucket threshold, or other data from inside the bucket.
261 size_t getPercentileBucketIdx(double pct, size_t level) const;
263 * Return the bucket index that the given percentile falls into (in the
264 * given historical interval). This index can then be used to retrieve either
265 * the bucket threshold, or other data from inside the bucket.
267 size_t getPercentileBucketIdx(double pct, TimePoint start, TimePoint end)
270 /* Get the bucket threshold for the bucket containing the given pct. */
271 ValueType getPercentileBucketMin(double pct, size_t level) const {
272 return getBucketMin(getPercentileBucketIdx(pct, level));
274 /* Get the bucket threshold for the bucket containing the given pct. */
275 ValueType getPercentileBucketMin(double pct, TimePoint start, TimePoint end)
277 return getBucketMin(getPercentileBucketIdx(pct, start, end));
281 * Print out serialized data from all buckets at the given level.
282 * Format is: BUCKET [',' BUCKET ...]
283 * Where: BUCKET == bucketMin ':' count ':' avg
285 std::string getString(size_t level) const;
288 * Print out serialized data for all buckets in the historical interval.
289 * For format, please see getString(size_t level).
291 std::string getString(TimePoint start, TimePoint end) const;
294 * Legacy APIs that accept a Duration parameters rather than TimePoint.
296 * These treat the Duration as relative to the clock epoch.
297 * Prefer using the correct TimePoint-based APIs instead. These APIs will
298 * eventually be deprecated and removed.
300 void update(Duration now) {
301 update(TimePoint(now));
303 void addValue(Duration now, const ValueType& value) {
304 addValue(TimePoint(now), value);
306 void addValue(Duration now, const ValueType& value, uint64_t times) {
307 addValue(TimePoint(now), value, times);
309 void addValues(Duration now, const folly::Histogram<ValueType>& values) {
310 addValues(TimePoint(now), values);
314 typedef ContainerType Bucket;
315 struct CountFromLevel {
316 explicit CountFromLevel(size_t level) : level_(level) {}
318 uint64_t operator()(const ContainerType& bucket) const {
319 return bucket.count(level_);
325 struct CountFromInterval {
326 explicit CountFromInterval(TimePoint start, TimePoint end)
327 : start_(start), end_(end) {}
329 uint64_t operator()(const ContainerType& bucket) const {
330 return bucket.count(start_, end_);
338 struct AvgFromLevel {
339 explicit AvgFromLevel(size_t level) : level_(level) {}
341 ValueType operator()(const ContainerType& bucket) const {
342 return bucket.template avg<ValueType>(level_);
349 template <typename ReturnType>
350 struct AvgFromInterval {
351 explicit AvgFromInterval(TimePoint start, TimePoint end)
352 : start_(start), end_(end) {}
354 ReturnType operator()(const ContainerType& bucket) const {
355 return bucket.template avg<ReturnType>(start_, end_);
364 * Special logic for the case of only one unique value registered
365 * (this can happen when clients don't pick good bucket ranges or have
366 * other bugs). It's a lot easier for clients to track down these issues
367 * if they are getting the correct value.
369 void maybeHandleSingleUniqueValue(const ValueType& value);
371 void computeAvgData(ValueType* total, uint64_t* nsamples, size_t level) const;
376 TimePoint end) const;
377 void computeRateData(ValueType* total, Duration* elapsed, size_t level) const;
378 void computeRateData(
382 TimePoint end) const;
384 folly::detail::HistogramBuckets<ValueType, ContainerType> buckets_;
385 bool haveNotSeenValue_;
386 bool singleUniqueValue_;
387 ValueType firstValue_;