2 * Copyright (C) 2005 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
20 #include <utils/Timers.h>
21 #include <utils/Log.h>
30 #ifdef HAVE_WIN32_THREADS
34 nsecs_t systemTime(int clock)
36 #if defined(HAVE_POSIX_CLOCKS)
37 static const clockid_t clocks[] = {
40 CLOCK_PROCESS_CPUTIME_ID,
41 CLOCK_THREAD_CPUTIME_ID
44 t.tv_sec = t.tv_nsec = 0;
45 clock_gettime(clocks[clock], &t);
46 return nsecs_t(t.tv_sec)*1000000000LL + t.tv_nsec;
48 // we don't support the clocks here.
50 t.tv_sec = t.tv_usec = 0;
51 gettimeofday(&t, NULL);
52 return nsecs_t(t.tv_sec)*1000000000LL + nsecs_t(t.tv_usec)*1000LL;
57 * ===========================================================================
59 * ===========================================================================
62 using namespace android;
65 void DurationTimer::start(void)
67 gettimeofday(&mStartWhen, NULL);
71 void DurationTimer::stop(void)
73 gettimeofday(&mStopWhen, NULL);
76 // Get the duration in microseconds.
77 long long DurationTimer::durationUsecs(void) const
79 return (long) subtractTimevals(&mStopWhen, &mStartWhen);
82 // Subtract two timevals. Returns the difference (ptv1-ptv2) in
84 /*static*/ long long DurationTimer::subtractTimevals(const struct timeval* ptv1,
85 const struct timeval* ptv2)
87 long long stop = ((long long) ptv1->tv_sec) * 1000000LL +
88 ((long long) ptv1->tv_usec);
89 long long start = ((long long) ptv2->tv_sec) * 1000000LL +
90 ((long long) ptv2->tv_usec);
94 // Add the specified amount of time to the timeval.
95 /*static*/ void DurationTimer::addToTimeval(struct timeval* ptv, long usec)
98 LOG(LOG_WARN, "", "Negative values not supported in addToTimeval\n");
102 // normalize tv_usec if necessary
103 if (ptv->tv_usec >= 1000000) {
104 ptv->tv_sec += ptv->tv_usec / 1000000;
105 ptv->tv_usec %= 1000000;
108 ptv->tv_usec += usec % 1000000;
109 if (ptv->tv_usec >= 1000000) {
110 ptv->tv_usec -= 1000000;
113 ptv->tv_sec += usec / 1000000;