sample_counter.h 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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_SAMPLE_COUNTER_H_
  11. #define RTC_BASE_NUMERICS_SAMPLE_COUNTER_H_
  12. #include <stdint.h>
  13. #include "absl/types/optional.h"
  14. namespace rtc {
  15. // Simple utility class for counting basic statistics (max./avg./variance) on
  16. // stream of samples.
  17. class SampleCounter {
  18. public:
  19. SampleCounter();
  20. ~SampleCounter();
  21. void Add(int sample);
  22. absl::optional<int> Avg(int64_t min_required_samples) const;
  23. absl::optional<int> Max() const;
  24. absl::optional<int64_t> Sum(int64_t min_required_samples) const;
  25. int64_t NumSamples() const;
  26. void Reset();
  27. // Adds all the samples from the |other| SampleCounter as if they were all
  28. // individually added using |Add(int)| method.
  29. void Add(const SampleCounter& other);
  30. protected:
  31. int64_t sum_ = 0;
  32. int64_t num_samples_ = 0;
  33. absl::optional<int> max_;
  34. };
  35. class SampleCounterWithVariance : public SampleCounter {
  36. public:
  37. SampleCounterWithVariance();
  38. ~SampleCounterWithVariance();
  39. void Add(int sample);
  40. absl::optional<int64_t> Variance(int64_t min_required_samples) const;
  41. void Reset();
  42. // Adds all the samples from the |other| SampleCounter as if they were all
  43. // individually added using |Add(int)| method.
  44. void Add(const SampleCounterWithVariance& other);
  45. private:
  46. int64_t sum_squared_ = 0;
  47. };
  48. } // namespace rtc
  49. #endif // RTC_BASE_NUMERICS_SAMPLE_COUNTER_H_