Codemod: use #include angle brackets in folly and thrift
[folly.git] / folly / stats / Histogram.h
1 /*
2  * Copyright 2014 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 #ifndef FOLLY_HISTOGRAM_H_
18 #define FOLLY_HISTOGRAM_H_
19
20 #include <cstddef>
21 #include <limits>
22 #include <ostream>
23 #include <string>
24 #include <vector>
25 #include <stdexcept>
26
27 #include <folly/detail/Stats.h>
28
29 namespace folly {
30
31 namespace detail {
32
33 /*
34  * A helper class to manage a set of histogram buckets.
35  */
36 template <typename T, typename BucketT>
37 class HistogramBuckets {
38  public:
39   typedef T ValueType;
40   typedef BucketT BucketType;
41
42   /*
43    * Create a set of histogram buckets.
44    *
45    * One bucket will be created for each bucketSize interval of values within
46    * the specified range.  Additionally, one bucket will be created to track
47    * all values that fall below the specified minimum, and one bucket will be
48    * created for all values above the specified maximum.
49    *
50    * If (max - min) is not a multiple of bucketSize, the last bucket will cover
51    * a smaller range of values than the other buckets.
52    *
53    * (max - min) must be larger than or equal to bucketSize.
54    */
55   HistogramBuckets(ValueType bucketSize, ValueType min, ValueType max,
56                    const BucketType& defaultBucket);
57
58   /* Returns the bucket size of each bucket in the histogram. */
59   ValueType getBucketSize() const {
60     return bucketSize_;
61   }
62
63   /* Returns the min value at which bucketing begins. */
64   ValueType getMin() const {
65     return min_;
66   }
67
68   /* Returns the max value at which bucketing ends. */
69   ValueType getMax() const {
70     return max_;
71   }
72
73   /*
74    * Returns the number of buckets.
75    *
76    * This includes the total number of buckets for the [min, max) range,
77    * plus 2 extra buckets, one for handling values less than min, and one for
78    * values greater than max.
79    */
80   unsigned int getNumBuckets() const {
81     return buckets_.size();
82   }
83
84   /* Returns the bucket index into which the given value would fall. */
85   unsigned int getBucketIdx(ValueType value) const;
86
87   /* Returns the bucket for the specified value */
88   BucketType& getByValue(ValueType value) {
89     return buckets_[getBucketIdx(value)];
90   }
91
92   /* Returns the bucket for the specified value */
93   const BucketType& getByValue(ValueType value) const {
94     return buckets_[getBucketIdx(value)];
95   }
96
97   /*
98    * Returns the bucket at the specified index.
99    *
100    * Note that index 0 is the bucket for all values less than the specified
101    * minimum.  Index 1 is the first bucket in the specified bucket range.
102    */
103   BucketType& getByIndex(unsigned int idx) {
104     return buckets_[idx];
105   }
106
107   /* Returns the bucket at the specified index. */
108   const BucketType& getByIndex(unsigned int idx) const {
109     return buckets_[idx];
110   }
111
112   /*
113    * Returns the minimum threshold for the bucket at the given index.
114    *
115    * The bucket at the specified index will store values in the range
116    * [bucketMin, bucketMin + bucketSize), or [bucketMin, max), if the overall
117    * max is smaller than bucketMin + bucketSize.
118    */
119   ValueType getBucketMin(unsigned int idx) const {
120     if (idx == 0) {
121       return std::numeric_limits<ValueType>::min();
122     }
123     if (idx == buckets_.size() - 1) {
124       return max_;
125     }
126
127     return min_ + ((idx - 1) * bucketSize_);
128   }
129
130   /*
131    * Returns the maximum threshold for the bucket at the given index.
132    *
133    * The bucket at the specified index will store values in the range
134    * [bucketMin, bucketMin + bucketSize), or [bucketMin, max), if the overall
135    * max is smaller than bucketMin + bucketSize.
136    */
137   ValueType getBucketMax(unsigned int idx) const {
138     if (idx == buckets_.size() - 1) {
139       return std::numeric_limits<ValueType>::max();
140     }
141
142     return min_ + (idx * bucketSize_);
143   }
144
145   /**
146    * Determine which bucket the specified percentile falls into.
147    *
148    * Looks for the bucket that contains the Nth percentile data point.
149    *
150    * @param pct     The desired percentile to find, as a value from 0.0 to 1.0.
151    * @param countFn A function that takes a const BucketType&, and returns the
152    *                number of values in that bucket.
153    * @param lowPct  The lowest percentile stored in the selected bucket will be
154    *                returned via this parameter.
155    * @param highPct The highest percentile stored in the selected bucket will
156    *                be returned via this parameter.
157    *
158    * @return Returns the index of the bucket that contains the Nth percentile
159    *         data point.
160    */
161   template <typename CountFn>
162   unsigned int getPercentileBucketIdx(double pct,
163                                       CountFn countFromBucket,
164                                       double* lowPct = nullptr,
165                                       double* highPct = nullptr) const;
166
167   /**
168    * Estimate the value at the specified percentile.
169    *
170    * @param pct     The desired percentile to find, as a value from 0.0 to 1.0.
171    * @param countFn A function that takes a const BucketType&, and returns the
172    *                number of values in that bucket.
173    * @param avgFn   A function that takes a const BucketType&, and returns the
174    *                average of all the values in that bucket.
175    *
176    * @return Returns an estimate for N, where N is the number where exactly pct
177    *         percentage of the data points in the histogram are less than N.
178    */
179   template <typename CountFn, typename AvgFn>
180   ValueType getPercentileEstimate(double pct,
181                                   CountFn countFromBucket,
182                                   AvgFn avgFromBucket) const;
183
184   /*
185    * Iterator access to the buckets.
186    *
187    * Note that the first bucket is for all values less than min, and the last
188    * bucket is for all values greater than max.  The buckets tracking values in
189    * the [min, max) actually start at the second bucket.
190    */
191   typename std::vector<BucketType>::const_iterator begin() const {
192     return buckets_.begin();
193   }
194   typename std::vector<BucketType>::iterator begin() {
195     return buckets_.begin();
196   }
197   typename std::vector<BucketType>::const_iterator end() const {
198     return buckets_.end();
199   }
200   typename std::vector<BucketType>::iterator end() {
201     return buckets_.end();
202   }
203
204  private:
205   ValueType bucketSize_;
206   ValueType min_;
207   ValueType max_;
208   std::vector<BucketType> buckets_;
209 };
210
211 } // detail
212
213
214 /*
215  * A basic histogram class.
216  *
217  * Groups data points into equally-sized buckets, and stores the overall sum of
218  * the data points in each bucket, as well as the number of data points in the
219  * bucket.
220  *
221  * The caller must specify the minimum and maximum data points to expect ahead
222  * of time, as well as the bucket width.
223  */
224 template <typename T>
225 class Histogram {
226  public:
227   typedef T ValueType;
228   typedef detail::Bucket<T> Bucket;
229
230   Histogram(ValueType bucketSize, ValueType min, ValueType max)
231     : buckets_(bucketSize, min, max, Bucket()) {}
232
233   /* Add a data point to the histogram */
234   void addValue(ValueType value) {
235     Bucket& bucket = buckets_.getByValue(value);
236     // TODO: It would be nice to handle overflow here.
237     bucket.sum += value;
238     bucket.count += 1;
239   }
240
241   /* Add multiple same data points to the histogram */
242   void addRepeatedValue(ValueType value, uint64_t nSamples) {
243     Bucket& bucket = buckets_.getByValue(value);
244     // TODO: It would be nice to handle overflow here.
245     bucket.sum += value * nSamples;
246     bucket.count += nSamples;
247   }
248
249   /*
250    * Remove a data point to the histogram
251    *
252    * Note that this method does not actually verify that this exact data point
253    * had previously been added to the histogram; it merely subtracts the
254    * requested value from the appropriate bucket's sum.
255    */
256   void removeValue(ValueType value) {
257     Bucket& bucket = buckets_.getByValue(value);
258     // TODO: It would be nice to handle overflow here.
259     if (bucket.count > 0) {
260       bucket.sum -= value;
261       bucket.count -= 1;
262     } else {
263       bucket.sum = ValueType();
264       bucket.count = 0;
265     }
266   }
267
268   /* Remove multiple same data points from the histogram */
269   void removeRepeatedValue(ValueType value, uint64_t nSamples) {
270     Bucket& bucket = buckets_.getByValue(value);
271     // TODO: It would be nice to handle overflow here.
272     if (bucket.count >= nSamples) {
273       bucket.sum -= value * nSamples;
274       bucket.count -= nSamples;
275     } else {
276       bucket.sum = ValueType();
277       bucket.count = 0;
278     }
279   }
280
281   /* Remove all data points from the histogram */
282   void clear() {
283     for (int i = 0; i < buckets_.getNumBuckets(); i++) {
284       buckets_.getByIndex(i).clear();
285     }
286   }
287
288   /* Subtract another histogram data from the histogram */
289   void subtract(const Histogram &hist) {
290     // the two histogram bucket definitions must match to support
291     // subtract.
292     if (getBucketSize() != hist.getBucketSize() ||
293         getMin() != hist.getMin() ||
294         getMax() != hist.getMax() ||
295         getNumBuckets() != hist.getNumBuckets() ) {
296       throw std::invalid_argument("Cannot subtract input histogram.");
297     }
298
299     for (int i = 0; i < buckets_.getNumBuckets(); i++) {
300       buckets_.getByIndex(i) -= hist.buckets_.getByIndex(i);
301     }
302   }
303
304   /* Merge two histogram data together */
305   void merge(const Histogram &hist) {
306     // the two histogram bucket definitions must match to support
307     // a merge.
308     if (getBucketSize() != hist.getBucketSize() ||
309         getMin() != hist.getMin() ||
310         getMax() != hist.getMax() ||
311         getNumBuckets() != hist.getNumBuckets() ) {
312       throw std::invalid_argument("Cannot merge from input histogram.");
313     }
314
315     for (int i = 0; i < buckets_.getNumBuckets(); i++) {
316       buckets_.getByIndex(i) += hist.buckets_.getByIndex(i);
317     }
318   }
319
320   /* Copy bucket values from another histogram */
321   void copy(const Histogram &hist) {
322     // the two histogram bucket definition must match
323     if (getBucketSize() != hist.getBucketSize() ||
324         getMin() != hist.getMin() ||
325         getMax() != hist.getMax() ||
326         getNumBuckets() != hist.getNumBuckets() ) {
327       throw std::invalid_argument("Cannot copy from input histogram.");
328     }
329
330     for (int i = 0; i < buckets_.getNumBuckets(); i++) {
331       buckets_.getByIndex(i) = hist.buckets_.getByIndex(i);
332     }
333   }
334
335   /* Returns the bucket size of each bucket in the histogram. */
336   ValueType getBucketSize() const {
337     return buckets_.getBucketSize();
338   }
339   /* Returns the min value at which bucketing begins. */
340   ValueType getMin() const {
341     return buckets_.getMin();
342   }
343   /* Returns the max value at which bucketing ends. */
344   ValueType getMax() const {
345     return buckets_.getMax();
346   }
347   /* Returns the number of buckets */
348   unsigned int getNumBuckets() const {
349     return buckets_.getNumBuckets();
350   }
351
352   /* Returns the specified bucket (for reading only!) */
353   const Bucket& getBucketByIndex(int idx) const {
354     return buckets_.getByIndex(idx);
355   }
356
357   /*
358    * Returns the minimum threshold for the bucket at the given index.
359    *
360    * The bucket at the specified index will store values in the range
361    * [bucketMin, bucketMin + bucketSize), or [bucketMin, max), if the overall
362    * max is smaller than bucketMin + bucketSize.
363    */
364   ValueType getBucketMin(unsigned int idx) const {
365     return buckets_.getBucketMin(idx);
366   }
367
368   /*
369    * Returns the maximum threshold for the bucket at the given index.
370    *
371    * The bucket at the specified index will store values in the range
372    * [bucketMin, bucketMin + bucketSize), or [bucketMin, max), if the overall
373    * max is smaller than bucketMin + bucketSize.
374    */
375   ValueType getBucketMax(unsigned int idx) const {
376     return buckets_.getBucketMax(idx);
377   }
378
379   /*
380    * Get the bucket that the specified percentile falls into
381    *
382    * The lowest and highest percentile data points in returned bucket will be
383    * returned in the lowPct and highPct arguments, if they are non-NULL.
384    */
385   unsigned int getPercentileBucketIdx(double pct,
386                                       double* lowPct = nullptr,
387                                       double* highPct = nullptr) const {
388     // We unfortunately can't use lambdas here yet;
389     // Some users of this code are still built with gcc-4.4.
390     CountFromBucket countFn;
391     return buckets_.getPercentileBucketIdx(pct, countFn, lowPct, highPct);
392   }
393
394   /**
395    * Estimate the value at the specified percentile.
396    *
397    * @param pct     The desired percentile to find, as a value from 0.0 to 1.0.
398    *
399    * @return Returns an estimate for N, where N is the number where exactly pct
400    *         percentage of the data points in the histogram are less than N.
401    */
402   ValueType getPercentileEstimate(double pct) const {
403     CountFromBucket countFn;
404     AvgFromBucket avgFn;
405     return buckets_.getPercentileEstimate(pct, countFn, avgFn);
406   }
407
408   /*
409    * Get a human-readable string describing the histogram contents
410    */
411   std::string debugString() const;
412
413   /*
414    * Write the histogram contents in tab-separated values (TSV) format.
415    * Format is "min max count sum".
416    */
417   void toTSV(std::ostream& out, bool skipEmptyBuckets = true) const;
418
419  private:
420   struct CountFromBucket {
421     uint64_t operator()(const Bucket& bucket) const {
422       return bucket.count;
423     }
424   };
425   struct AvgFromBucket {
426     ValueType operator()(const Bucket& bucket) const {
427       if (bucket.count == 0) {
428         return ValueType(0);
429       }
430       // Cast bucket.count to a signed integer type.  This ensures that we
431       // perform division properly here: If bucket.sum is a signed integer
432       // type but we divide by an unsigned number, unsigned division will be
433       // performed and bucket.sum will be converted to unsigned first.
434       // If bucket.sum is unsigned, the code will still do unsigned division
435       // correctly.
436       //
437       // The only downside is if bucket.count is large enough to be negative
438       // when treated as signed.  That should be extremely unlikely, though.
439       return bucket.sum / static_cast<int64_t>(bucket.count);
440     }
441   };
442
443   detail::HistogramBuckets<ValueType, Bucket> buckets_;
444 };
445
446 } // folly
447
448 #endif // FOLLY_HISTOGRAM_H_