gethrxtime.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /* gethrxtime -- get high resolution real time
  2. Copyright (C) 2005-2007, 2009-2020 Free Software Foundation, Inc.
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 3 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <https://www.gnu.org/licenses/>. */
  13. /* Written by Paul Eggert. */
  14. #include <config.h>
  15. #define GETHRXTIME_INLINE _GL_EXTERN_INLINE
  16. #include "gethrxtime.h"
  17. #if ! (HAVE_ARITHMETIC_HRTIME_T && HAVE_DECL_GETHRTIME)
  18. #include "timespec.h"
  19. /* Get the current time, as a count of the number of nanoseconds since
  20. an arbitrary epoch (e.g., the system boot time). Prefer a
  21. high-resolution clock that is not subject to resetting or
  22. drifting. */
  23. xtime_t
  24. gethrxtime (void)
  25. {
  26. # if HAVE_NANOUPTIME
  27. {
  28. struct timespec ts;
  29. nanouptime (&ts);
  30. return xtime_make (ts.tv_sec, ts.tv_nsec);
  31. }
  32. # else
  33. # if defined CLOCK_MONOTONIC && HAVE_CLOCK_GETTIME
  34. {
  35. struct timespec ts;
  36. if (clock_gettime (CLOCK_MONOTONIC, &ts) == 0)
  37. return xtime_make (ts.tv_sec, ts.tv_nsec);
  38. }
  39. # endif
  40. # if HAVE_MICROUPTIME
  41. {
  42. struct timeval tv;
  43. microuptime (&tv);
  44. return xtime_make (tv.tv_sec, 1000 * tv.tv_usec);
  45. }
  46. # else
  47. /* No monotonically increasing clocks are available; fall back on a
  48. clock that might jump backwards, since it's the best we can do. */
  49. {
  50. struct timespec ts;
  51. timespec_get(&ts, TIME_UTC);
  52. return xtime_make (ts.tv_sec, ts.tv_nsec);
  53. }
  54. # endif
  55. # endif
  56. }
  57. #endif