Timers.cpp 2.0 KB

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