ua_clock.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. # ifdef SLIST_ENTRY
  7. # undef SLIST_ENTRY /* Fix redefinition of SLIST_ENTRY on mingw winnt.h */
  8. # endif
  9. # include <windows.h>
  10. #else
  11. # include <sys/time.h>
  12. #endif
  13. #if defined(__APPLE__) || defined(__MACH__)
  14. # include <mach/clock.h>
  15. # include <mach/mach.h>
  16. #endif
  17. UA_DateTime UA_DateTime_now(void) {
  18. #if defined(_WIN32)
  19. /* Windows filetime has the same definition as UA_DateTime */
  20. FILETIME ft;
  21. SYSTEMTIME st;
  22. GetSystemTime(&st);
  23. SystemTimeToFileTime(&st, &ft);
  24. ULARGE_INTEGER ul;
  25. ul.LowPart = ft.dwLowDateTime;
  26. ul.HighPart = ft.dwHighDateTime;
  27. return (UA_DateTime)ul.QuadPart;
  28. #else
  29. struct timeval tv;
  30. gettimeofday(&tv, NULL);
  31. return (tv.tv_sec * UA_SEC_TO_DATETIME) + (tv.tv_usec * UA_USEC_TO_DATETIME) + UA_DATETIME_UNIX_EPOCH;
  32. #endif
  33. }
  34. UA_DateTime UA_DateTime_nowMonotonic(void) {
  35. #if defined(_WIN32)
  36. LARGE_INTEGER freq, ticks;
  37. QueryPerformanceFrequency(&freq);
  38. QueryPerformanceCounter(&ticks);
  39. UA_Double ticks2dt = UA_SEC_TO_DATETIME / (UA_Double)freq.QuadPart;
  40. return (UA_DateTime)(ticks.QuadPart * ticks2dt);
  41. #elif defined(__APPLE__) || defined(__MACH__)
  42. /* OS X does not have clock_gettime, use clock_get_time */
  43. clock_serv_t cclock;
  44. mach_timespec_t mts;
  45. host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock);
  46. clock_get_time(cclock, &mts);
  47. mach_port_deallocate(mach_task_self(), cclock);
  48. return (mts.tv_sec * UA_SEC_TO_DATETIME) + (mts.tv_nsec / 100);
  49. #elif !defined(CLOCK_MONOTONIC_RAW)
  50. struct timespec ts;
  51. clock_gettime(CLOCK_MONOTONIC, &ts);
  52. return (ts.tv_sec * UA_SEC_TO_DATETIME) + (ts.tv_nsec / 100);
  53. #else
  54. struct timespec ts;
  55. clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
  56. return (ts.tv_sec * UA_SEC_TO_DATETIME) + (ts.tv_nsec / 100);
  57. #endif
  58. }