1 /*
2  * Copyright (C) 2008 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 
18 /*
19  * System clock functions.
20  */
21 
22 #define LOG_TAG "SystemClock"
23 
24 #include <utils/SystemClock.h>
25 
26 #include <string.h>
27 #include <errno.h>
28 #include <time.h>
29 
30 #include <cutils/compiler.h>
31 
32 #include <utils/Timers.h>
33 #include <utils/Log.h>
34 
35 namespace android {
36 
37 /*
38  * native public static long uptimeMillis();
39  */
uptimeMillis()40 int64_t uptimeMillis()
41 {
42     int64_t when = systemTime(SYSTEM_TIME_MONOTONIC);
43     return (int64_t) nanoseconds_to_milliseconds(when);
44 }
45 
46 /*
47  * native public static long elapsedRealtime();
48  */
elapsedRealtime()49 int64_t elapsedRealtime()
50 {
51 	return nanoseconds_to_milliseconds(elapsedRealtimeNano());
52 }
53 
54 /*
55  * native public static long elapsedRealtimeNano();
56  */
elapsedRealtimeNano()57 int64_t elapsedRealtimeNano()
58 {
59 #if defined(__linux__)
60     struct timespec ts;
61     int err = clock_gettime(CLOCK_BOOTTIME, &ts);
62     if (CC_UNLIKELY(err)) {
63         // This should never happen, but just in case ...
64         ALOGE("clock_gettime(CLOCK_BOOTTIME) failed: %s", strerror(errno));
65         return 0;
66     }
67 
68     return seconds_to_nanoseconds(ts.tv_sec) + ts.tv_nsec;
69 #else
70     return systemTime(SYSTEM_TIME_MONOTONIC);
71 #endif
72 }
73 
74 }; // namespace android
75