Upstreaming browser/ui/uikit_ui_util from iOS.
[chromium-blink-merge.git] / remoting / base / rate_counter.cc
blobe6532da165541fb06c21cee39032572cf7b8627e
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.
5 #include "remoting/base/rate_counter.h"
7 #include "base/logging.h"
9 namespace remoting {
11 RateCounter::RateCounter(base::TimeDelta time_window)
12 : time_window_(time_window),
13 sum_(0) {
14 DCHECK_GT(time_window.InMilliseconds(), 0);
17 RateCounter::~RateCounter() {
20 void RateCounter::Record(int64 value) {
21 DCHECK(CalledOnValidThread());
23 base::Time current_time = CurrentTime();
24 EvictOldDataPoints(current_time);
25 sum_ += value;
26 data_points_.push(std::make_pair(current_time, value));
29 double RateCounter::Rate() {
30 DCHECK(CalledOnValidThread());
32 EvictOldDataPoints(CurrentTime());
33 return sum_ / time_window_.InSecondsF();
36 void RateCounter::SetCurrentTimeForTest(base::Time current_time) {
37 DCHECK(CalledOnValidThread());
38 DCHECK(current_time >= current_time_for_test_);
40 current_time_for_test_ = current_time;
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_;
47 while (!data_points_.empty()) {
48 if (data_points_.front().first > window_start)
49 break;
51 sum_ -= data_points_.front().second;
52 data_points_.pop();
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_;
62 } // namespace remoting