• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (C) 2019 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #ifndef ICING_UTIL_CLOCK_H_
16 #define ICING_UTIL_CLOCK_H_
17 
18 #include <cstdint>
19 #include <memory>
20 
21 namespace icing {
22 namespace lib {
23 
24 // Returns the current steady time in nanoseconds. The steady clock is different
25 // from the system clock. It's monotonic and never returns a lower value than a
26 // previous call, while a system clock can be occasionally adjusted.
27 int64_t GetSteadyTimeNanoseconds();
28 
29 // Returns the current steady time in Milliseconds. The steady clock is
30 // different from the system clock. It's monotonic and never returns a lower
31 // value than a previous call, while a system clock can be occasionally
32 // adjusted.
33 int64_t GetSteadyTimeMilliseconds();
34 
35 // Used to calculate the elapsed time.
36 class Timer {
37  public:
38   // Creates and starts the timer.
Timer()39   Timer() : start_timestamp_nanoseconds_(GetSteadyTimeNanoseconds()) {}
40 
41   virtual ~Timer() = default;
42 
43   // Returns the elapsed time from when timer started.
GetElapsedMilliseconds()44   virtual int64_t GetElapsedMilliseconds() {
45     return GetElapsedNanoseconds() / 1000000;
46   }
47 
48   // Returns the elapsed time from when timer started.
GetElapsedNanoseconds()49   virtual int64_t GetElapsedNanoseconds() {
50     return GetSteadyTimeNanoseconds() - start_timestamp_nanoseconds_;
51   }
52 
53  private:
54   int64_t start_timestamp_nanoseconds_;
55 };
56 
57 // Wrapper around real-time clock functions. This is separated primarily so
58 // tests can override this clock and inject it into the class under test.
59 class Clock {
60  public:
61   virtual ~Clock() = default;
62 
63   // Returns the current time in milliseconds, it's guaranteed that the return
64   // value is non-negative.
65   virtual int64_t GetSystemTimeMilliseconds() const;
66 
67   // Returns a timer used to calculate the elapsed time. The timer starts when
68   // the method returns.
69   virtual std::unique_ptr<Timer> GetNewTimer() const;
70 };
71 
72 }  // namespace lib
73 }  // namespace icing
74 
75 #endif  // ICING_UTIL_CLOCK_H_
76