- add sources.
[platform/framework/web/crosswalk.git] / src / remoting / base / rate_counter.h
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 #ifndef REMOTING_BASE_RATE_COUNTER_H_
6 #define REMOTING_BASE_RATE_COUNTER_H_
7
8 #include <queue>
9 #include <utility>
10
11 #include "base/basictypes.h"
12 #include "base/threading/non_thread_safe.h"
13 #include "base/time/time.h"
14
15 namespace remoting {
16
17 // Measures average rate per second of a sequence of point rate samples
18 // over a specified time window. This can be used to measure bandwidth, frame
19 // rates, etc.
20 class RateCounter : public base::NonThreadSafe {
21  public:
22   // Constructs a rate counter over the specified |time_window|.
23   explicit RateCounter(base::TimeDelta time_window);
24   virtual ~RateCounter();
25
26   // Records a point event count to include in the rate.
27   void Record(int64 value);
28
29   // Returns the rate-per-second of values recorded over the time window.
30   // Note that rates reported before |time_window| has elapsed are not accurate.
31   double Rate();
32
33   // Overrides the current time for testing.
34   void SetCurrentTimeForTest(base::Time current_time);
35
36  private:
37   // Type used to store data points with timestamps.
38   typedef std::pair<base::Time, int64> DataPoint;
39
40   // Removes data points more than |time_window| older than |current_time|.
41   void EvictOldDataPoints(base::Time current_time);
42
43   // Returns the current time specified for test, if set, or base::Time::Now().
44   base::Time CurrentTime() const;
45
46   // Time window over which to calculate the rate.
47   const base::TimeDelta time_window_;
48
49   // Queue containing data points in the order in which they were recorded.
50   std::queue<DataPoint> data_points_;
51
52   // Sum of values in |data_points_|.
53   int64 sum_;
54
55   // If set, used to calculate the running average, in place of Now().
56   base::Time current_time_for_test_;
57
58   DISALLOW_COPY_AND_ASSIGN(RateCounter);
59 };
60
61 }  // namespace remoting
62
63 #endif  // REMOTING_BASE_RATE_COUNTER_H_