1 // Copyright (c) 2019 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 QUICHE_QUIC_CORE_QUIC_TIME_ACCUMULATOR_H_ 6 #define QUICHE_QUIC_CORE_QUIC_TIME_ACCUMULATOR_H_ 7 8 #include "quiche/quic/core/quic_time.h" 9 #include "quiche/quic/platform/api/quic_export.h" 10 #include "quiche/quic/platform/api/quic_logging.h" 11 12 namespace quic { 13 14 // QuicTimeAccumulator accumulates elapsed times between Start(s) and Stop(s). 15 class QUICHE_EXPORT QuicTimeAccumulator { 16 // TODO(wub): Switch to a data member called kNotRunningSentinel after c++17. NotRunningSentinel()17 static constexpr QuicTime NotRunningSentinel() { 18 return QuicTime::Infinite(); 19 } 20 21 public: 22 // True if Started and not Stopped. IsRunning()23 bool IsRunning() const { return last_start_time_ != NotRunningSentinel(); } 24 Start(QuicTime now)25 void Start(QuicTime now) { 26 QUICHE_DCHECK(!IsRunning()); 27 last_start_time_ = now; 28 QUICHE_DCHECK(IsRunning()); 29 } 30 Stop(QuicTime now)31 void Stop(QuicTime now) { 32 QUICHE_DCHECK(IsRunning()); 33 if (now > last_start_time_) { 34 total_elapsed_ = total_elapsed_ + (now - last_start_time_); 35 } 36 last_start_time_ = NotRunningSentinel(); 37 QUICHE_DCHECK(!IsRunning()); 38 } 39 40 // Get total elapsed time between COMPLETED Start/Stop pairs. GetTotalElapsedTime()41 QuicTime::Delta GetTotalElapsedTime() const { return total_elapsed_; } 42 43 // Get total elapsed time between COMPLETED Start/Stop pairs, plus, if it is 44 // running, the elapsed time between |last_start_time_| and |now|. GetTotalElapsedTime(QuicTime now)45 QuicTime::Delta GetTotalElapsedTime(QuicTime now) const { 46 if (!IsRunning()) { 47 return total_elapsed_; 48 } 49 if (now <= last_start_time_) { 50 return total_elapsed_; 51 } 52 return total_elapsed_ + (now - last_start_time_); 53 } 54 55 private: 56 // 57 // |last_start_time_| 58 // | 59 // V 60 // Start => Stop => Start => Stop => Start 61 // | | | | 62 // |___________| + |___________| = |total_elapsed_| 63 QuicTime::Delta total_elapsed_ = QuicTime::Delta::Zero(); 64 QuicTime last_start_time_ = NotRunningSentinel(); 65 }; 66 67 } // namespace quic 68 69 #endif // QUICHE_QUIC_CORE_QUIC_TIME_ACCUMULATOR_H_ 70