moving_average.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright 2015 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 MEDIA_BASE_MOVING_AVERAGE_H_
  5. #define MEDIA_BASE_MOVING_AVERAGE_H_
  6. #include <stddef.h>
  7. #include <stdint.h>
  8. #include <utility>
  9. #include <vector>
  10. #include "base/time/time.h"
  11. #include "media/base/media_export.h"
  12. #include "media/base/timestamp_constants.h"
  13. namespace media {
  14. // Simple class for calculating a moving average of fixed size.
  15. class MEDIA_EXPORT MovingAverage {
  16. public:
  17. // Creates a MovingAverage instance with space for |depth| samples.
  18. explicit MovingAverage(size_t depth);
  19. MovingAverage(const MovingAverage&) = delete;
  20. MovingAverage& operator=(const MovingAverage&) = delete;
  21. ~MovingAverage();
  22. // Adds a new sample to the average; replaces the oldest sample if |depth_|
  23. // has been exceeded. Updates |total_| to the new sum of values.
  24. void AddSample(base::TimeDelta sample);
  25. // Returns the current average of all held samples.
  26. base::TimeDelta Average() const;
  27. // Returns the population standard deviation of all held samples.
  28. base::TimeDelta Deviation() const;
  29. // Resets the state of the class to its initial post-construction state.
  30. void Reset();
  31. uint64_t count() const { return count_; }
  32. base::TimeDelta max() const { return max_; }
  33. size_t depth() const { return depth_; }
  34. // |first| is min, |second| is max of all samples in the window.
  35. std::pair<base::TimeDelta, base::TimeDelta> GetMinAndMax();
  36. private:
  37. // Maximum number of elements allowed in the average.
  38. const size_t depth_;
  39. std::vector<base::TimeDelta> samples_;
  40. // Number of elements seen thus far.
  41. uint64_t count_ = 0;
  42. base::TimeDelta total_;
  43. // Maximum value ever seen.
  44. base::TimeDelta max_ = kNoTimestamp;
  45. };
  46. } // namespace media
  47. #endif // MEDIA_BASE_MOVING_AVERAGE_H_