xref: /aosp_15_r20/external/cronet/base/timer/elapsed_timer.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2013 The Chromium Authors
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 BASE_TIMER_ELAPSED_TIMER_H_
6 #define BASE_TIMER_ELAPSED_TIMER_H_
7 
8 #include "base/base_export.h"
9 #include "base/time/time.h"
10 
11 namespace base {
12 
13 // A simple wrapper around TimeTicks::Now().
14 class BASE_EXPORT ElapsedTimer {
15  public:
16   ElapsedTimer();
17 
18   ElapsedTimer(const ElapsedTimer&) = delete;
19   ElapsedTimer& operator=(const ElapsedTimer&) = delete;
20 
21   ElapsedTimer(ElapsedTimer&& other);
22 
23   void operator=(ElapsedTimer&& other);
24 
25   // Returns the time elapsed since object construction.
26   TimeDelta Elapsed() const;
27 
28   // Returns the timestamp of the creation of this timer.
start_time()29   TimeTicks start_time() const { return start_time_; }
30 
31  private:
32   TimeTicks start_time_;
33 };
34 
35 // A simple wrapper around ThreadTicks::Now().
36 class BASE_EXPORT ElapsedThreadTimer {
37  public:
38   ElapsedThreadTimer();
39 
40   ElapsedThreadTimer(const ElapsedThreadTimer&) = delete;
41   ElapsedThreadTimer& operator=(const ElapsedThreadTimer&) = delete;
42 
43   // Returns the ThreadTicks time elapsed since object construction.
44   // Only valid if |is_supported()| returns true, otherwise returns TimeDelta().
45   TimeDelta Elapsed() const;
46 
is_supported()47   bool is_supported() const { return is_supported_; }
48 
49  private:
50   const bool is_supported_;
51   const ThreadTicks begin_;
52 };
53 
54 // Whenever there's a ScopedMockElapsedTimersForTest in scope,
55 // Elapsed(Thread)Timers will always return kMockElapsedTime from Elapsed().
56 // This is useful, for example, in unit tests that verify that their impl
57 // records timing histograms. It enables such tests to observe reliable timings.
58 class BASE_EXPORT ScopedMockElapsedTimersForTest {
59  public:
60   static constexpr TimeDelta kMockElapsedTime = Milliseconds(1337);
61 
62   // ScopedMockElapsedTimersForTest is not thread-safe (it must be instantiated
63   // in a test before other threads begin using ElapsedTimers; and it must
64   // conversely outlive any usage of ElapsedTimer in that test).
65   ScopedMockElapsedTimersForTest();
66 
67   ScopedMockElapsedTimersForTest(const ScopedMockElapsedTimersForTest&) =
68       delete;
69   ScopedMockElapsedTimersForTest& operator=(
70       const ScopedMockElapsedTimersForTest&) = delete;
71 
72   ~ScopedMockElapsedTimersForTest();
73 };
74 
75 }  // namespace base
76 
77 #endif  // BASE_TIMER_ELAPSED_TIMER_H_
78