rate_counter.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright (c) 2011 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 REMOTING_BASE_RATE_COUNTER_H_
  5. #define REMOTING_BASE_RATE_COUNTER_H_
  6. #include <stdint.h>
  7. #include <utility>
  8. #include "base/containers/queue.h"
  9. #include "base/memory/raw_ptr.h"
  10. #include "base/sequence_checker.h"
  11. #include "base/time/default_tick_clock.h"
  12. #include "base/time/tick_clock.h"
  13. #include "base/time/time.h"
  14. namespace remoting {
  15. // Measures average rate per second of a sequence of point rate samples
  16. // over a specified time window. This can be used to measure bandwidth, frame
  17. // rates, etc.
  18. class RateCounter {
  19. public:
  20. // Constructs a rate counter over the specified |time_window|.
  21. explicit RateCounter(base::TimeDelta time_window);
  22. RateCounter(const RateCounter&) = delete;
  23. RateCounter& operator=(const RateCounter&) = delete;
  24. virtual ~RateCounter();
  25. // Records a point event count to include in the rate.
  26. void Record(int64_t value);
  27. // Returns the rate-per-second of values recorded over the time window.
  28. // Note that rates reported before |time_window| has elapsed are not accurate.
  29. double Rate() const;
  30. void set_tick_clock_for_tests(const base::TickClock* tick_clock) {
  31. tick_clock_ = tick_clock;
  32. }
  33. private:
  34. // Type used to store data points with timestamps.
  35. typedef std::pair<base::TimeTicks, int64_t> DataPoint;
  36. // Removes data points more than |time_window| older than |current_time|.
  37. void EvictOldDataPoints(base::TimeTicks current_time);
  38. // Time window over which to calculate the rate.
  39. const base::TimeDelta time_window_;
  40. // Queue containing data points in the order in which they were recorded.
  41. base::queue<DataPoint> data_points_;
  42. // Sum of values in |data_points_|.
  43. int64_t sum_;
  44. raw_ptr<const base::TickClock> tick_clock_ =
  45. base::DefaultTickClock::GetInstance();
  46. SEQUENCE_CHECKER(sequence_checker_);
  47. };
  48. } // namespace remoting
  49. #endif // REMOTING_BASE_RATE_COUNTER_H_