moving_average.h 2.1 KB

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