1 /*
2  *  Copyright (c) 2019 The WebRTC project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 #include "rtc_base/numerics/event_rate_counter.h"
11 
12 #include <algorithm>
13 
14 namespace webrtc {
15 
AddEvent(Timestamp event_time)16 void EventRateCounter::AddEvent(Timestamp event_time) {
17   if (first_time_.IsFinite())
18     interval_.AddSample(event_time - last_time_);
19   first_time_ = std::min(first_time_, event_time);
20   last_time_ = std::max(last_time_, event_time);
21   event_count_++;
22 }
23 
AddEvents(EventRateCounter other)24 void EventRateCounter::AddEvents(EventRateCounter other) {
25   first_time_ = std::min(first_time_, other.first_time_);
26   last_time_ = std::max(last_time_, other.last_time_);
27   event_count_ += other.event_count_;
28   interval_.AddSamples(other.interval_);
29 }
30 
IsEmpty() const31 bool EventRateCounter::IsEmpty() const {
32   return first_time_ == last_time_;
33 }
34 
Rate() const35 double EventRateCounter::Rate() const {
36   if (event_count_ == 0)
37     return 0;
38   if (event_count_ == 1)
39     return NAN;
40   return (event_count_ - 1) / (last_time_ - first_time_).seconds<double>();
41 }
42 
TotalDuration() const43 TimeDelta EventRateCounter::TotalDuration() const {
44   if (first_time_.IsInfinite()) {
45     return TimeDelta::Zero();
46   }
47   return last_time_ - first_time_;
48 }
49 }  // namespace webrtc
50