rate_tracker.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * Copyright 2015 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_RATE_TRACKER_H_
  11. #define RTC_BASE_RATE_TRACKER_H_
  12. #include <stdint.h>
  13. #include <stdlib.h>
  14. namespace rtc {
  15. // Computes units per second over a given interval by tracking the units over
  16. // each bucket of a given size and calculating the instantaneous rate assuming
  17. // that over each bucket the rate was constant.
  18. class RateTracker {
  19. public:
  20. RateTracker(int64_t bucket_milliseconds, size_t bucket_count);
  21. virtual ~RateTracker();
  22. // Computes the average rate over the most recent interval_milliseconds,
  23. // or if the first sample was added within this period, computes the rate
  24. // since the first sample was added.
  25. double ComputeRateForInterval(int64_t interval_milliseconds) const;
  26. // Computes the average rate over the rate tracker's recording interval
  27. // of bucket_milliseconds * bucket_count.
  28. double ComputeRate() const {
  29. return ComputeRateForInterval(bucket_milliseconds_ *
  30. static_cast<int64_t>(bucket_count_));
  31. }
  32. // Computes the average rate since the first sample was added to the
  33. // rate tracker.
  34. double ComputeTotalRate() const;
  35. // The total number of samples added.
  36. int64_t TotalSampleCount() const;
  37. // Reads the current time in order to determine the appropriate bucket for
  38. // these samples, and increments the count for that bucket by sample_count.
  39. void AddSamples(int64_t sample_count);
  40. protected:
  41. // overrideable for tests
  42. virtual int64_t Time() const;
  43. private:
  44. void EnsureInitialized();
  45. size_t NextBucketIndex(size_t bucket_index) const;
  46. const int64_t bucket_milliseconds_;
  47. const size_t bucket_count_;
  48. int64_t* sample_buckets_;
  49. size_t total_sample_count_;
  50. size_t current_bucket_;
  51. int64_t bucket_start_time_milliseconds_;
  52. int64_t initialization_time_milliseconds_;
  53. };
  54. } // namespace rtc
  55. #endif // RTC_BASE_RATE_TRACKER_H_