2 * Copyright 2016 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.
21 #include <type_traits>
23 namespace folly { namespace detail {
26 * Helper function to compute the average, given a specified input type and
30 // If the input is long double, divide using long double to avoid losing
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);
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,
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);
53 * Helper function to compute the rate per Interval,
54 * given the specified count recorded over the elapsed time period.
56 template <typename ReturnType=double,
57 typename TimeType=std::chrono::seconds,
58 typename Interval=TimeType>
59 ReturnType rateHelper(ReturnType count, TimeType elapsed) {
60 if (elapsed == TimeType(0)) {
64 // Use std::chrono::duration_cast to convert between the native
65 // duration and the desired interval. However, convert the rates,
66 // rather than just converting the elapsed duration. Converting the
67 // elapsed time first may collapse it down to 0 if the elapsed interval
68 // is less than the desired interval, which will incorrectly result in
70 typedef std::chrono::duration<
71 ReturnType, std::ratio<TimeType::period::den,
72 TimeType::period::num>> NativeRate;
73 typedef std::chrono::duration<
74 ReturnType, std::ratio<Interval::period::den,
75 Interval::period::num>> DesiredRate;
77 NativeRate native(count / elapsed.count());
78 DesiredRate desired = std::chrono::duration_cast<DesiredRate>(native);
79 return desired.count();
97 void add(const ValueType& s, uint64_t c) {
98 // TODO: It would be nice to handle overflow here.
103 Bucket& operator+=(const Bucket& o) {
108 Bucket& operator-=(const Bucket& o) {
109 // TODO: It would be nice to handle overflow here.
115 template <typename ReturnType>
116 ReturnType avg() const {
117 return avgHelper<ReturnType>(sum, count);