moving_average.cc 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. #include "base/power_monitor/moving_average.h"
  5. #include <algorithm>
  6. #include <limits>
  7. #include "base/check_op.h"
  8. #include "base/numerics/clamped_math.h"
  9. namespace {
  10. constexpr int kIntMax = std::numeric_limits<int>::max();
  11. constexpr int64_t kInt64Max = std::numeric_limits<int64_t>::max();
  12. } // namespace
  13. namespace base {
  14. MovingAverage::MovingAverage(uint8_t window_size)
  15. : window_size_(window_size), buffer_(window_size, 0) {
  16. DCHECK_LE(kIntMax * window_size, kInt64Max);
  17. }
  18. MovingAverage::~MovingAverage() = default;
  19. void MovingAverage::AddSample(int sample) {
  20. sum_ -= buffer_[index_];
  21. buffer_[index_++] = sample;
  22. sum_ += sample;
  23. if (index_ == window_size_) {
  24. full_ = true;
  25. index_ = 0;
  26. }
  27. }
  28. int MovingAverage::GetAverageRoundedDown() const {
  29. if (Size() == 0 || uint64_t{Size()} > static_cast<uint64_t>(kInt64Max)) {
  30. return 0;
  31. }
  32. return static_cast<int>(sum_ / static_cast<int64_t>(Size()));
  33. }
  34. int MovingAverage::GetAverageRoundedToClosest() const {
  35. if (Size() == 0 || uint64_t{Size()} > static_cast<uint64_t>(kInt64Max))
  36. return 0;
  37. return static_cast<int>((base::ClampedNumeric<int64_t>(sum_) + Size() / 2) /
  38. static_cast<int64_t>(Size()));
  39. }
  40. double MovingAverage::GetUnroundedAverage() const {
  41. if (Size() == 0)
  42. return 0;
  43. return sum_ / static_cast<double>(Size());
  44. }
  45. void MovingAverage::Reset() {
  46. std::fill(buffer_.begin(), buffer_.end(), 0);
  47. sum_ = 0;
  48. index_ = 0;
  49. full_ = false;
  50. }
  51. size_t MovingAverage::Size() const {
  52. return full_ ? window_size_ : index_;
  53. }
  54. } // namespace base