1 /*
2 * Copyright (C) 2005 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 #include <utils/Timers.h>
18
19 #include <limits.h>
20 #include <stdlib.h>
21 #include <time.h>
22
23 #include <android-base/macros.h>
24 #include <utils/Log.h>
25
26 static constexpr size_t clock_id_max = 5;
27
checkClockId(int clock)28 static void checkClockId(int clock) {
29 LOG_ALWAYS_FATAL_IF(clock < 0 || clock >= clock_id_max, "invalid clock id");
30 }
31
32 #if defined(__linux__)
systemTime(int clock)33 nsecs_t systemTime(int clock) {
34 checkClockId(clock);
35 static constexpr clockid_t clocks[] = {CLOCK_REALTIME, CLOCK_MONOTONIC,
36 CLOCK_PROCESS_CPUTIME_ID, CLOCK_THREAD_CPUTIME_ID,
37 CLOCK_BOOTTIME};
38 static_assert(clock_id_max == arraysize(clocks));
39 timespec t = {};
40 clock_gettime(clocks[clock], &t);
41 return nsecs_t(t.tv_sec)*1000000000LL + t.tv_nsec;
42 }
43 #else
systemTime(int clock)44 nsecs_t systemTime(int clock) {
45 // TODO: is this ever called with anything but REALTIME on mac/windows?
46 checkClockId(clock);
47
48 // Clock support varies widely across hosts. Mac OS doesn't support
49 // CLOCK_BOOTTIME (and doesn't even have clock_gettime until 10.12).
50 // Windows is windows.
51 timeval t = {};
52 gettimeofday(&t, nullptr);
53 return nsecs_t(t.tv_sec)*1000000000LL + nsecs_t(t.tv_usec)*1000LL;
54 }
55 #endif
56
toMillisecondTimeoutDelay(nsecs_t referenceTime,nsecs_t timeoutTime)57 int toMillisecondTimeoutDelay(nsecs_t referenceTime, nsecs_t timeoutTime) {
58 if (timeoutTime <= referenceTime) return 0;
59
60 uint64_t timeoutDelay = uint64_t(timeoutTime - referenceTime);
61 if (timeoutDelay > uint64_t((INT_MAX - 1) * 1000000LL)) return -1;
62 return (timeoutDelay + 999999LL) / 1000000LL;
63 }
64