• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2020 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef BASE_POWER_MONITOR_MOVING_AVERAGE_H_
6 #define BASE_POWER_MONITOR_MOVING_AVERAGE_H_
7 
8 #include <stddef.h>
9 #include <stdint.h>
10 
11 #include <vector>
12 
13 #include "base/base_export.h"
14 
15 namespace base {
16 
17 // Calculates average over a small fixed size window. If there are less than
18 // window size elements, calculates average of all inserted elements so far.
19 // This implementation support a maximum window size of 255.
20 // Ported from third_party/webrtc/rtc_base/numerics/moving_average.h.
21 class BASE_EXPORT MovingAverage {
22  public:
23   // Maximum supported window size is 2^8 - 1 = 255.
24   explicit MovingAverage(uint8_t window_size);
25   ~MovingAverage();
26   // MovingAverage is neither copyable nor movable.
27   MovingAverage(const MovingAverage&) = delete;
28   MovingAverage& operator=(const MovingAverage&) = delete;
29 
30   // Adds new sample. If the window is full, the oldest element is pushed out.
31   void AddSample(int sample);
32 
33   // Returns rounded down average of last `window_size` elements or all
34   // elements if there are not enough of them.
35   int GetAverageRoundedDown() const;
36 
37   // Same as above but rounded to the closest integer.
38   int GetAverageRoundedToClosest() const;
39 
40   // Returns unrounded average over the window.
41   double GetUnroundedAverage() const;
42 
43   // Resets to the initial state before any elements were added.
44   void Reset();
45 
46   // Returns number of elements in the window.
47   size_t Size() const;
48 
49  private:
50   // Stores `window_size` used in the constructor.
51   uint8_t window_size_ = 0;
52   // New samples are added at this index. Counts modulo `window_size`.
53   uint8_t index_ = 0;
54   // Set to true when the `buffer_` is full. i.e, all elements contain a
55   // sample added by AddSample().
56   bool full_ = false;
57   // Sum of the samples in the moving window.
58   int64_t sum_ = 0;
59   // Circular buffer for all the samples in the moving window.
60   // Size is always `window_size`
61   std::vector<int> buffer_;
62 };
63 
64 }  // namespace base
65 
66 #endif  // BASE_POWER_MONITOR_MOVING_AVERAGE_H_
67