xref: /aosp_15_r20/external/cronet/base/time/time_android.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2018 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 #include "base/time/time.h"
6 
7 namespace base {
8 
9 // static
FromUptimeMillis(int64_t uptime_millis_value)10 TimeTicks TimeTicks::FromUptimeMillis(int64_t uptime_millis_value) {
11   // The implementation of the SystemClock.uptimeMillis() in AOSP uses the same
12   // clock as base::TimeTicks::Now(): clock_gettime(CLOCK_MONOTONIC), see in
13   // platform/system/code:
14   // 1. libutils/SystemClock.cpp
15   // 2. libutils/Timers.cpp
16   //
17   // We are not aware of any motivations for Android OEMs to modify the AOSP
18   // implementation of either uptimeMillis() or clock_gettime(CLOCK_MONOTONIC),
19   // so we assume that there are no such customizations.
20   //
21   // Under these assumptions the conversion is as safe as copying the value of
22   // base::TimeTicks::Now() with a loss of sub-millisecond precision.
23   return TimeTicks(uptime_millis_value * Time::kMicrosecondsPerMillisecond);
24 }
25 
26 // This file is included on chromeos_ash because it needs to interpret
27 // UptimeMillis values from the Android container.
28 #if BUILDFLAG(IS_ANDROID)
29 
30 // static
FromJavaNanoTime(int64_t nano_time_value)31 TimeTicks TimeTicks::FromJavaNanoTime(int64_t nano_time_value) {
32   // The implementation of the System.nanoTime() in AOSP uses the same
33   // clock as UptimeMillis() and base::TimeTicks::Now():
34   // clock_gettime(CLOCK_MONOTONIC), see ojluni/src/main/native/System.c in
35   // AOSP.
36   //
37   // From Android documentation on android.os.SystemClock:
38   //   [uptimeMillis()] is the basis for most interval timing such as
39   //   Thread.sleep(millls), Object.wait(millis), and System.nanoTime().
40   //
41   // We are not aware of any motivations for Android OEMs to modify the AOSP
42   // implementation of either uptimeMillis(), nanoTime, or
43   // clock_gettime(CLOCK_MONOTONIC), so we assume that there are no such
44   // customizations.
45   //
46   // Under these assumptions the conversion is as safe as copying the value of
47   // base::TimeTicks::Now() without the (theoretical) sub-microsecond
48   // resolution.
49   return TimeTicks(nano_time_value / Time::kNanosecondsPerMicrosecond);
50 }
51 
ToUptimeMillis() const52 jlong TimeTicks::ToUptimeMillis() const {
53   // See FromUptimeMillis. UptimeMillis and TimeTicks use the same clock source,
54   // and only differ in resolution.
55   return us_ / Time::kMicrosecondsPerMillisecond;
56 }
57 
ToUptimeMicros() const58 jlong TimeTicks::ToUptimeMicros() const {
59   // Same as ToUptimeMillis but maintains sub-millisecond precision.
60   return us_;
61 }
62 
63 #endif  // BUILDFLAG(IS_ANDROID)
64 
65 }  // namespace base
66