Add BucketedTimeSeries to folly
[folly.git] / folly / detail / Stats.h
1 /*
2  * Copyright 2012 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
22 namespace folly { namespace detail {
23
24 template<typename T>
25 struct Bucket {
26  public:
27   typedef T ValueType;
28
29   Bucket()
30     : sum(ValueType()),
31       count(0) {}
32
33   void clear() {
34     sum = ValueType();
35     count = 0;
36   }
37
38   void add(const ValueType& s, uint64_t c) {
39     // TODO: It would be nice to handle overflow here.
40     sum += s;
41     count += c;
42   }
43
44   Bucket& operator+=(const Bucket& o) {
45     add(o.sum, o.count);
46     return *this;
47   }
48
49   Bucket& operator-=(const Bucket& o) {
50     // TODO: It would be nice to handle overflow here.
51     sum -= o.sum;
52     count -= o.count;
53     return *this;
54   }
55
56   template <typename ReturnType>
57   ReturnType avg() const {
58     return (count ?
59             static_cast<ReturnType>(sum) / count :
60             ReturnType(0));
61   }
62
63   ValueType sum;
64   uint64_t count;
65 };
66
67 }} // folly::detail
68
69 #endif // FOLLY_DETAIL_STATS_H_