rate_counter.cc 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. #include "remoting/base/rate_counter.h"
  5. #include "base/check_op.h"
  6. namespace remoting {
  7. RateCounter::RateCounter(base::TimeDelta time_window)
  8. : time_window_(time_window), sum_(0) {
  9. DCHECK_GT(time_window, base::TimeDelta());
  10. }
  11. RateCounter::~RateCounter() {
  12. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  13. }
  14. void RateCounter::Record(int64_t value) {
  15. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  16. base::TimeTicks now = tick_clock_->NowTicks();
  17. EvictOldDataPoints(now);
  18. sum_ += value;
  19. data_points_.push(std::make_pair(now, value));
  20. }
  21. double RateCounter::Rate() const {
  22. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  23. // This is just to ensure the rate is up to date.
  24. const_cast<RateCounter*>(this)->EvictOldDataPoints(tick_clock_->NowTicks());
  25. return sum_ / time_window_.InSecondsF();
  26. }
  27. void RateCounter::EvictOldDataPoints(base::TimeTicks now) {
  28. // Remove data points outside of the window.
  29. base::TimeTicks window_start = now - time_window_;
  30. while (!data_points_.empty()) {
  31. if (data_points_.front().first > window_start)
  32. break;
  33. sum_ -= data_points_.front().second;
  34. data_points_.pop();
  35. }
  36. }
  37. } // namespace remoting