You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
1.5 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  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. #include "rtc_base/numerics/moving_average.h"
  11. #include <algorithm>
  12. #include "rtc_base/checks.h"
  13. namespace rtc {
  14. MovingAverage::MovingAverage(size_t window_size) : history_(window_size, 0) {
  15. // Limit window size to avoid overflow.
  16. RTC_DCHECK_LE(window_size, (int64_t{1} << 32) - 1);
  17. }
  18. MovingAverage::~MovingAverage() = default;
  19. void MovingAverage::AddSample(int sample) {
  20. count_++;
  21. size_t index = count_ % history_.size();
  22. if (count_ > history_.size())
  23. sum_ -= history_[index];
  24. sum_ += sample;
  25. history_[index] = sample;
  26. }
  27. absl::optional<int> MovingAverage::GetAverageRoundedDown() const {
  28. if (count_ == 0)
  29. return absl::nullopt;
  30. return sum_ / Size();
  31. }
  32. absl::optional<int> MovingAverage::GetAverageRoundedToClosest() const {
  33. if (count_ == 0)
  34. return absl::nullopt;
  35. return (sum_ + Size() / 2) / Size();
  36. }
  37. absl::optional<double> MovingAverage::GetUnroundedAverage() const {
  38. if (count_ == 0)
  39. return absl::nullopt;
  40. return sum_ / static_cast<double>(Size());
  41. }
  42. void MovingAverage::Reset() {
  43. count_ = 0;
  44. sum_ = 0;
  45. }
  46. size_t MovingAverage::Size() const {
  47. return std::min(count_, history_.size());
  48. }
  49. } // namespace rtc