blob: 5293cd2a829836c75f718bb16890c0b09393d78d [file] [log] [blame]
The Android Open Source Projectcbb10112009-03-03 19:31:44 -08001/*
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>
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080021#include <utils/Log.h>
22
23#include <stdlib.h>
24#include <stdio.h>
25#include <unistd.h>
26#include <sys/time.h>
27#include <time.h>
28#include <errno.h>
Jeff Brown43550ee2011-03-17 01:34:19 -070029#include <limits.h>
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080030
31#ifdef HAVE_WIN32_THREADS
32#include <windows.h>
33#endif
34
35nsecs_t systemTime(int clock)
36{
37#if defined(HAVE_POSIX_CLOCKS)
38 static const clockid_t clocks[] = {
39 CLOCK_REALTIME,
40 CLOCK_MONOTONIC,
41 CLOCK_PROCESS_CPUTIME_ID,
Nick Pellyaf1e7b72012-07-19 09:17:24 -070042 CLOCK_THREAD_CPUTIME_ID,
43 CLOCK_BOOTTIME
The Android Open Source Projectcbb10112009-03-03 19:31:44 -080044 };
45 struct timespec t;
46 t.tv_sec = t.tv_nsec = 0;
47 clock_gettime(clocks[clock], &t);
48 return nsecs_t(t.tv_sec)*1000000000LL + t.tv_nsec;
49#else
50 // we don't support the clocks here.
51 struct timeval t;
52 t.tv_sec = t.tv_usec = 0;
53 gettimeofday(&t, NULL);
54 return nsecs_t(t.tv_sec)*1000000000LL + nsecs_t(t.tv_usec)*1000LL;
55#endif
56}
57
Jeff Brown43550ee2011-03-17 01:34:19 -070058int toMillisecondTimeoutDelay(nsecs_t referenceTime, nsecs_t timeoutTime)
59{
60 int timeoutDelayMillis;
61 if (timeoutTime > referenceTime) {
62 uint64_t timeoutDelay = uint64_t(timeoutTime - referenceTime);
63 if (timeoutDelay > uint64_t((INT_MAX - 1) * 1000000LL)) {
64 timeoutDelayMillis = -1;
65 } else {
66 timeoutDelayMillis = (timeoutDelay + 999999LL) / 1000000LL;
67 }
68 } else {
69 timeoutDelayMillis = 0;
70 }
71 return timeoutDelayMillis;
72}