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