Home | History | Annotate | Download | only in base
      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 
      5 #include "remoting/base/rate_counter.h"
      6 
      7 #include "base/logging.h"
      8 
      9 namespace remoting {
     10 
     11 RateCounter::RateCounter(base::TimeDelta time_window)
     12     : time_window_(time_window),
     13       sum_(0) {
     14   DCHECK_GT(time_window.InMilliseconds(), 0);
     15 }
     16 
     17 RateCounter::~RateCounter() {
     18 }
     19 
     20 void RateCounter::Record(int64 value) {
     21   DCHECK(CalledOnValidThread());
     22 
     23   base::Time current_time = CurrentTime();
     24   EvictOldDataPoints(current_time);
     25   sum_ += value;
     26   data_points_.push(std::make_pair(current_time, value));
     27 }
     28 
     29 double RateCounter::Rate() {
     30   DCHECK(CalledOnValidThread());
     31 
     32   EvictOldDataPoints(CurrentTime());
     33   return sum_ / time_window_.InSecondsF();
     34 }
     35 
     36 void RateCounter::SetCurrentTimeForTest(base::Time current_time) {
     37   DCHECK(CalledOnValidThread());
     38   DCHECK(current_time >= current_time_for_test_);
     39 
     40   current_time_for_test_ = current_time;
     41 }
     42 
     43 void RateCounter::EvictOldDataPoints(base::Time current_time) {
     44   // Remove data points outside of the window.
     45   base::Time window_start = current_time - time_window_;
     46 
     47   while (!data_points_.empty()) {
     48     if (data_points_.front().first > window_start)
     49       break;
     50 
     51     sum_ -= data_points_.front().second;
     52     data_points_.pop();
     53   }
     54 }
     55 
     56 base::Time RateCounter::CurrentTime() const {
     57   if (current_time_for_test_ == base::Time())
     58     return base::Time::Now();
     59   return current_time_for_test_;
     60 }
     61 
     62 }  // namespace remoting
     63