ua_clock.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. /* Enable POSIX features */
  9. #if !defined(_XOPEN_SOURCE)
  10. # define _XOPEN_SOURCE 600
  11. #endif
  12. #ifndef _DEFAULT_SOURCE
  13. # define _DEFAULT_SOURCE
  14. #endif
  15. /* On older systems we need to define _BSD_SOURCE.
  16. * _DEFAULT_SOURCE is an alias for that. */
  17. #ifndef _BSD_SOURCE
  18. # define _BSD_SOURCE
  19. #endif
  20. #include <time.h>
  21. #include <sys/time.h>
  22. #if defined(__APPLE__) || defined(__MACH__)
  23. # include <mach/clock.h>
  24. # include <mach/mach.h>
  25. #endif
  26. #include "ua_types.h"
  27. UA_DateTime UA_DateTime_now(void) {
  28. struct timeval tv;
  29. gettimeofday(&tv, NULL);
  30. return (tv.tv_sec * UA_DATETIME_SEC) + (tv.tv_usec * UA_DATETIME_USEC) + UA_DATETIME_UNIX_EPOCH;
  31. }
  32. /* Credit to https://stackoverflow.com/questions/13804095/get-the-time-zone-gmt-offset-in-c */
  33. UA_Int64 UA_DateTime_localTimeUtcOffset(void) {
  34. time_t gmt, rawtime = time(NULL);
  35. struct tm *ptm;
  36. struct tm gbuf;
  37. ptm = gmtime_r(&rawtime, &gbuf);
  38. // Request that mktime() looksup dst in timezone database
  39. ptm->tm_isdst = -1;
  40. gmt = mktime(ptm);
  41. return (UA_Int64) (difftime(rawtime, gmt) * UA_DATETIME_SEC);
  42. }
  43. UA_DateTime UA_DateTime_nowMonotonic(void) {
  44. #if 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_DATETIME_SEC) + (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_DATETIME_SEC) + (ts.tv_nsec / 100);
  56. #else
  57. struct timespec ts;
  58. clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
  59. return (ts.tv_sec * UA_DATETIME_SEC) + (ts.tv_nsec / 100);
  60. #endif
  61. }