OLD | NEW |
(Empty) | |
| 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 namespace remoting { |
| 8 |
| 9 RateCounter::RateCounter(base::TimeDelta time_window) |
| 10 : time_window_(time_window), |
| 11 sum_(0) { |
| 12 } |
| 13 |
| 14 RateCounter::~RateCounter() { |
| 15 } |
| 16 |
| 17 void RateCounter::Record(int64 value) { |
| 18 base::Time current_time = base::Time::Now(); |
| 19 Evict(current_time); |
| 20 |
| 21 base::AutoLock auto_lock(lock_); |
| 22 sum_ += value; |
| 23 data_points_.push(std::make_pair(current_time, value)); |
| 24 } |
| 25 |
| 26 double RateCounter::Rate() { |
| 27 Evict(base::Time::Now()); |
| 28 |
| 29 base::AutoLock auto_lock(lock_); |
| 30 return static_cast<double>(base::Time::kMillisecondsPerSecond) * sum_ / |
| 31 time_window_.InMilliseconds(); |
| 32 } |
| 33 |
| 34 void RateCounter::Evict(base::Time current_time) { |
| 35 base::AutoLock auto_lock(lock_); |
| 36 |
| 37 // Remove data points outside of the window. |
| 38 base::Time window_start = current_time - time_window_; |
| 39 |
| 40 while (!data_points_.empty()) { |
| 41 if (data_points_.front().first > window_start) |
| 42 break; |
| 43 |
| 44 sum_ -= data_points_.front().second; |
| 45 data_points_.pop(); |
| 46 } |
| 47 } |
| 48 |
| 49 } // namespace remoting |
OLD | NEW |