ua_clock.c 2.2 KB

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