1 // Copyright 2013 the V8 project 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 #ifndef V8_BASE_PLATFORM_ELAPSED_TIMER_H_
6 #define V8_BASE_PLATFORM_ELAPSED_TIMER_H_
8 #include "src/base/logging.h"
9 #include "src/base/platform/time.h"
14 class ElapsedTimer V8_FINAL {
17 ElapsedTimer() : started_(false) {}
20 // Starts this timer. Once started a timer can be checked with
21 // |Elapsed()| or |HasExpired()|, and may be restarted using |Restart()|.
22 // This method must not be called on an already started timer.
32 // Stops this timer. Must not be called on a timer that was not
36 start_ticks_ = TimeTicks();
43 // Returns |true| if this timer was started previously.
44 bool IsStarted() const {
45 DCHECK(started_ || start_ticks_.IsNull());
46 DCHECK(!started_ || !start_ticks_.IsNull());
47 return !start_ticks_.IsNull();
50 // Restarts the timer and returns the time elapsed since the previous start.
51 // This method is equivalent to obtaining the elapsed time with |Elapsed()|
52 // and then starting the timer again, but does so in one single operation,
53 // avoiding the need to obtain the clock value twice. It may only be called
54 // on a previously started timer.
57 TimeTicks ticks = Now();
58 TimeDelta elapsed = ticks - start_ticks_;
59 DCHECK(elapsed.InMicroseconds() >= 0);
65 // Returns the time elapsed since the previous start. This method may only
66 // be called on a previously started timer.
67 TimeDelta Elapsed() const {
69 TimeDelta elapsed = Now() - start_ticks_;
70 DCHECK(elapsed.InMicroseconds() >= 0);
74 // Returns |true| if the specified |time_delta| has elapsed since the
75 // previous start, or |false| if not. This method may only be called on
76 // a previously started timer.
77 bool HasExpired(TimeDelta time_delta) const {
79 return Elapsed() >= time_delta;
83 static V8_INLINE TimeTicks Now() {
84 TimeTicks now = TimeTicks::HighResolutionNow();
85 DCHECK(!now.IsNull());
89 TimeTicks start_ticks_;
95 } } // namespace v8::base
97 #endif // V8_BASE_PLATFORM_ELAPSED_TIMER_H_