ua_clock.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. *
  4. * Copyright 2016-2017 (c) Fraunhofer IOSB (Author: Julius Pfrommer)
  5. * Copyright 2017 (c) Stefan Profanter, fortiss GmbH
  6. * Copyright 2017 (c) Thomas Stalder, Blue Time Concept SA
  7. */
  8. #include "ua_types.h"
  9. #include <time.h>
  10. #include <sys/time.h>
  11. #if defined(__APPLE__) || defined(__MACH__)
  12. # include <mach/clock.h>
  13. # include <mach/mach.h>
  14. #endif
  15. UA_DateTime UA_DateTime_now(void) {
  16. struct timeval tv;
  17. gettimeofday(&tv, NULL);
  18. return (tv.tv_sec * UA_DATETIME_SEC) + (tv.tv_usec * UA_DATETIME_USEC) + UA_DATETIME_UNIX_EPOCH;
  19. }
  20. /* Credit to https://stackoverflow.com/questions/13804095/get-the-time-zone-gmt-offset-in-c */
  21. UA_Int64 UA_DateTime_localTimeUtcOffset(void) {
  22. time_t gmt, rawtime = time(NULL);
  23. struct tm *ptm;
  24. struct tm gbuf;
  25. ptm = gmtime_r(&rawtime, &gbuf);
  26. // Request that mktime() looksup dst in timezone database
  27. ptm->tm_isdst = -1;
  28. gmt = mktime(ptm);
  29. return (UA_Int64) (difftime(rawtime, gmt) * UA_DATETIME_SEC);
  30. }
  31. UA_DateTime UA_DateTime_nowMonotonic(void) {
  32. #if defined(__APPLE__) || defined(__MACH__)
  33. /* OS X does not have clock_gettime, use clock_get_time */
  34. clock_serv_t cclock;
  35. mach_timespec_t mts;
  36. host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock);
  37. clock_get_time(cclock, &mts);
  38. mach_port_deallocate(mach_task_self(), cclock);
  39. return (mts.tv_sec * UA_DATETIME_SEC) + (mts.tv_nsec / 100);
  40. #elif !defined(CLOCK_MONOTONIC_RAW)
  41. struct timespec ts;
  42. clock_gettime(CLOCK_MONOTONIC, &ts);
  43. return (ts.tv_sec * UA_DATETIME_SEC) + (ts.tv_nsec / 100);
  44. #else
  45. struct timespec ts;
  46. clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
  47. return (ts.tv_sec * UA_DATETIME_SEC) + (ts.tv_nsec / 100);
  48. #endif
  49. }