1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 /* Calculate the rolling mean of a series of values. */
9 #ifndef mozilla_RollingMean_h_
10 #define mozilla_RollingMean_h_
12 #include "mozilla/Assertions.h"
13 #include "mozilla/Vector.h"
16 #include <type_traits>
21 * RollingMean<T> calculates a rolling mean of the values it is given. It
22 * accumulates the total as values are added and removed. The second type
23 * argument S specifies the type of the total. This may need to be a bigger
24 * type in order to maintain that the sum of all values in the average doesn't
25 * exceed the maximum input value.
27 * WARNING: Float types are not supported due to rounding errors.
29 template <typename T
, typename S
>
38 static_assert(!std::is_floating_point_v
<T
>,
39 "floating-point types are unsupported due to rounding "
42 explicit RollingMean(size_t aMaxValues
)
43 : mInsertIndex(0), mMaxValues(aMaxValues
), mTotal(0) {
44 MOZ_ASSERT(aMaxValues
> 0);
47 RollingMean
& operator=(RollingMean
&& aOther
) = default;
50 * Insert a value into the rolling mean.
52 bool insert(T aValue
) {
53 MOZ_ASSERT(mValues
.length() <= mMaxValues
);
55 if (mValues
.length() == mMaxValues
) {
56 mTotal
= mTotal
- mValues
[mInsertIndex
] + aValue
;
57 mValues
[mInsertIndex
] = aValue
;
59 if (!mValues
.append(aValue
)) {
62 mTotal
= mTotal
+ aValue
;
65 mInsertIndex
= (mInsertIndex
+ 1) % mMaxValues
;
70 * Calculate the rolling mean.
74 return T(mTotal
/ int64_t(mValues
.length()));
77 bool empty() const { return mValues
.empty(); }
80 * Remove all values from the rolling mean.
88 size_t maxValues() const { return mMaxValues
; }
91 } // namespace mozilla
93 #endif // mozilla_RollingMean_h_