diff options
Diffstat (limited to 'libutils/Timers.cpp')
-rw-r--r-- | libutils/Timers.cpp | 40 |
1 files changed, 23 insertions, 17 deletions
diff --git a/libutils/Timers.cpp b/libutils/Timers.cpp index 1172ae7841..fd3f4a9576 100644 --- a/libutils/Timers.cpp +++ b/libutils/Timers.cpp @@ -20,31 +20,37 @@ #include <utils/Timers.h> #include <limits.h> +#include <stdlib.h> #include <time.h> -// host linux support requires Linux 2.6.39+ +#include <android-base/macros.h> + +static constexpr size_t clock_id_max = 5; + +static void checkClockId(int clock) { + if (clock < 0 || clock >= clock_id_max) abort(); +} + #if defined(__linux__) -nsecs_t systemTime(int clock) -{ - static const clockid_t clocks[] = { - CLOCK_REALTIME, - CLOCK_MONOTONIC, - CLOCK_PROCESS_CPUTIME_ID, - CLOCK_THREAD_CPUTIME_ID, - CLOCK_BOOTTIME - }; - struct timespec t; - t.tv_sec = t.tv_nsec = 0; +nsecs_t systemTime(int clock) { + checkClockId(clock); + static constexpr clockid_t clocks[] = {CLOCK_REALTIME, CLOCK_MONOTONIC, + CLOCK_PROCESS_CPUTIME_ID, CLOCK_THREAD_CPUTIME_ID, + CLOCK_BOOTTIME}; + static_assert(clock_id_max == arraysize(clocks)); + timespec t = {}; clock_gettime(clocks[clock], &t); return nsecs_t(t.tv_sec)*1000000000LL + t.tv_nsec; } #else -nsecs_t systemTime(int /*clock*/) -{ +nsecs_t systemTime(int clock) { + // TODO: is this ever called with anything but REALTIME on mac/windows? + checkClockId(clock); + // Clock support varies widely across hosts. Mac OS doesn't support - // CLOCK_BOOTTIME, and Windows is windows. - struct timeval t; - t.tv_sec = t.tv_usec = 0; + // CLOCK_BOOTTIME (and doesn't even have clock_gettime until 10.12). + // Windows is windows. + timeval t = {}; gettimeofday(&t, nullptr); return nsecs_t(t.tv_sec)*1000000000LL + nsecs_t(t.tv_usec)*1000LL; } |