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 //
18 // Timer functions.
19 //
20
21 #define LOG_TAG "Timers"
22
23 #include <limits.h>
24 #include <time.h>
25
26 #include "Timers.h"
27
28 #if defined(__ANDROID__)
systemTime(int clock)29 nsecs_t systemTime(int clock) {
30 static const clockid_t clocks[] = {CLOCK_REALTIME, CLOCK_MONOTONIC, CLOCK_PROCESS_CPUTIME_ID,
31 CLOCK_THREAD_CPUTIME_ID, CLOCK_BOOTTIME};
32 struct timespec t;
33 t.tv_sec = t.tv_nsec = 0;
34 clock_gettime(clocks[clock], &t);
35 return nsecs_t(t.tv_sec) * 1000000000LL + t.tv_nsec;
36 }
37 #else
systemTime(int)38 nsecs_t systemTime(int /*clock*/) {
39 // Clock support varies widely across hosts. Mac OS doesn't support
40 // posix clocks, older glibcs don't support CLOCK_BOOTTIME and Windows
41 // is windows.
42 struct timeval t;
43 t.tv_sec = t.tv_usec = 0;
44 gettimeofday(&t, NULL);
45 return nsecs_t(t.tv_sec) * 1000000000LL + nsecs_t(t.tv_usec) * 1000LL;
46 }
47 #endif
48
toMillisecondTimeoutDelay(nsecs_t referenceTime,nsecs_t timeoutTime)49 int toMillisecondTimeoutDelay(nsecs_t referenceTime, nsecs_t timeoutTime) {
50 nsecs_t timeoutDelayMillis;
51 if (timeoutTime > referenceTime) {
52 uint64_t timeoutDelay = uint64_t(timeoutTime - referenceTime);
53 if (timeoutDelay > uint64_t((INT_MAX - 1) * 1000000LL)) {
54 timeoutDelayMillis = -1;
55 } else {
56 timeoutDelayMillis = (timeoutDelay + 999999LL) / 1000000LL;
57 }
58 } else {
59 timeoutDelayMillis = 0;
60 }
61 return (int)timeoutDelayMillis;
62 }
63