3e5ef06ffc5b7aa2bf1e1c5dc42aad4885c1277b
[folly.git] / folly / detail / Stats.h
1 /*
2  * Copyright 2013 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_DETAIL_STATS_H_
18 #define FOLLY_DETAIL_STATS_H_
19
20 #include <cstdint>
21 #include <type_traits>
22
23 namespace folly { namespace detail {
24
25 /*
26  * Helper function to compute the average, given a specified input type and
27  * return type.
28  */
29
30 // If the input is long double, divide using long double to avoid losing
31 // precision.
32 template <typename ReturnType>
33 ReturnType avgHelper(long double sum, uint64_t count) {
34   if (count == 0) { return ReturnType(0); }
35   const long double countf = count;
36   return static_cast<ReturnType>(sum / countf);
37 }
38
39 // In all other cases divide using double precision.
40 // This should be relatively fast, and accurate enough for most use cases.
41 template <typename ReturnType, typename ValueType>
42 typename std::enable_if<!std::is_same<typename std::remove_cv<ValueType>::type,
43                                       long double>::value,
44                         ReturnType>::type
45 avgHelper(ValueType sum, uint64_t count) {
46   if (count == 0) { return ReturnType(0); }
47   const double sumf = sum;
48   const double countf = count;
49   return static_cast<ReturnType>(sumf / countf);
50 }
51
52
53 template<typename T>
54 struct Bucket {
55  public:
56   typedef T ValueType;
57
58   Bucket()
59     : sum(ValueType()),
60       count(0) {}
61
62   void clear() {
63     sum = ValueType();
64     count = 0;
65   }
66
67   void add(const ValueType& s, uint64_t c) {
68     // TODO: It would be nice to handle overflow here.
69     sum += s;
70     count += c;
71   }
72
73   Bucket& operator+=(const Bucket& o) {
74     add(o.sum, o.count);
75     return *this;
76   }
77
78   Bucket& operator-=(const Bucket& o) {
79     // TODO: It would be nice to handle overflow here.
80     sum -= o.sum;
81     count -= o.count;
82     return *this;
83   }
84
85   template <typename ReturnType>
86   ReturnType avg() const {
87     return avgHelper<ReturnType>(sum, count);
88   }
89
90   ValueType sum;
91   uint64_t count;
92 };
93
94 }} // folly::detail
95
96 #endif // FOLLY_DETAIL_STATS_H_