moving_average.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * Copyright (c) 2018 The WebRTC project authors. All Rights Reserved.
  3. *
  4. * Use of this source code is governed by a BSD-style license
  5. * that can be found in the LICENSE file in the root of the source
  6. * tree. An additional intellectual property rights grant can be found
  7. * in the file PATENTS. All contributing project authors may
  8. * be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #ifndef RTC_BASE_NUMERICS_MOVING_AVERAGE_H_
  11. #define RTC_BASE_NUMERICS_MOVING_AVERAGE_H_
  12. #include <stddef.h>
  13. #include <stdint.h>
  14. #include <vector>
  15. #include "absl/types/optional.h"
  16. namespace rtc {
  17. // Calculates average over fixed size window. If there are less than window
  18. // size elements, calculates average of all inserted so far elements.
  19. //
  20. class MovingAverage {
  21. public:
  22. // Maximum supported window size is 2^32 - 1.
  23. explicit MovingAverage(size_t window_size);
  24. ~MovingAverage();
  25. // MovingAverage is neither copyable nor movable.
  26. MovingAverage(const MovingAverage&) = delete;
  27. MovingAverage& operator=(const MovingAverage&) = delete;
  28. // Adds new sample. If the window is full, the oldest element is pushed out.
  29. void AddSample(int sample);
  30. // Returns rounded down average of last |window_size| elements or all
  31. // elements if there are not enough of them. Returns nullopt if there were
  32. // no elements added.
  33. absl::optional<int> GetAverageRoundedDown() const;
  34. // Same as above but rounded to the closest integer.
  35. absl::optional<int> GetAverageRoundedToClosest() const;
  36. // Returns unrounded average over the window.
  37. absl::optional<double> GetUnroundedAverage() const;
  38. // Resets to the initial state before any elements were added.
  39. void Reset();
  40. // Returns number of elements in the window.
  41. size_t Size() const;
  42. private:
  43. // Total number of samples added to the class since last reset.
  44. size_t count_ = 0;
  45. // Sum of the samples in the moving window.
  46. int64_t sum_ = 0;
  47. // Circular buffer for all the samples in the moving window.
  48. // Size is always |window_size|
  49. std::vector<int> history_;
  50. };
  51. } // namespace rtc
  52. #endif // RTC_BASE_NUMERICS_MOVING_AVERAGE_H_