ua_clock.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. /* This work is licensed under a Creative Commons CCZero 1.0 Universal License.
  5. * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. */
  6. #include "ua_types.h"
  7. #include <time.h>
  8. #ifdef _WIN32
  9. # ifdef SLIST_ENTRY
  10. # undef SLIST_ENTRY /* Fix redefinition of SLIST_ENTRY on mingw winnt.h */
  11. # endif
  12. # include <windows.h>
  13. #else
  14. # include <sys/time.h>
  15. #endif
  16. #if defined(__APPLE__) || defined(__MACH__)
  17. # include <mach/clock.h>
  18. # include <mach/mach.h>
  19. #endif
  20. UA_DateTime UA_DateTime_now(void) {
  21. #if defined(_WIN32)
  22. /* Windows filetime has the same definition as UA_DateTime */
  23. FILETIME ft;
  24. SYSTEMTIME st;
  25. GetSystemTime(&st);
  26. SystemTimeToFileTime(&st, &ft);
  27. ULARGE_INTEGER ul;
  28. ul.LowPart = ft.dwLowDateTime;
  29. ul.HighPart = ft.dwHighDateTime;
  30. return (UA_DateTime)ul.QuadPart;
  31. #else
  32. struct timeval tv;
  33. gettimeofday(&tv, NULL);
  34. return (tv.tv_sec * UA_SEC_TO_DATETIME) + (tv.tv_usec * UA_USEC_TO_DATETIME) + UA_DATETIME_UNIX_EPOCH;
  35. #endif
  36. }
  37. UA_DateTime UA_DateTime_nowMonotonic(void) {
  38. #if defined(_WIN32)
  39. LARGE_INTEGER freq, ticks;
  40. QueryPerformanceFrequency(&freq);
  41. QueryPerformanceCounter(&ticks);
  42. UA_Double ticks2dt = UA_SEC_TO_DATETIME / (UA_Double)freq.QuadPart;
  43. return (UA_DateTime)(ticks.QuadPart * ticks2dt);
  44. #elif defined(__APPLE__) || defined(__MACH__)
  45. /* OS X does not have clock_gettime, use clock_get_time */
  46. clock_serv_t cclock;
  47. mach_timespec_t mts;
  48. host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock);
  49. clock_get_time(cclock, &mts);
  50. mach_port_deallocate(mach_task_self(), cclock);
  51. return (mts.tv_sec * UA_SEC_TO_DATETIME) + (mts.tv_nsec / 100);
  52. #elif !defined(CLOCK_MONOTONIC_RAW)
  53. struct timespec ts;
  54. clock_gettime(CLOCK_MONOTONIC, &ts);
  55. return (ts.tv_sec * UA_SEC_TO_DATETIME) + (ts.tv_nsec / 100);
  56. #else
  57. struct timespec ts;
  58. clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
  59. return (ts.tv_sec * UA_SEC_TO_DATETIME) + (ts.tv_nsec / 100);
  60. #endif
  61. }