clock_gettime.c 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. * Check: a unit test framework for C
  3. * Copyright (C) 2001, 2002 Arien Malec
  4. *
  5. * This library is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU Lesser General Public
  7. * License as published by the Free Software Foundation; either
  8. * version 2.1 of the License, or (at your option) any later version.
  9. *
  10. * This library is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. * Lesser General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Lesser General Public
  16. * License along with this library; if not, write to the
  17. * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
  18. * MA 02110-1301, USA.
  19. */
  20. #include "libcompat.h"
  21. #ifdef __APPLE__
  22. #include <mach/clock.h>
  23. #include <mach/mach.h>
  24. #include <mach/mach_time.h>
  25. #include <CoreServices/CoreServices.h>
  26. #include <unistd.h>
  27. #endif
  28. #define NANOSECONDS_PER_SECOND 1000000000
  29. int clock_gettime(clockid_t clk_id CK_ATTRIBUTE_UNUSED, struct timespec *ts)
  30. {
  31. #ifdef __APPLE__
  32. /* Some versions of macOS and iOS do not have clock_gettime, use
  33. * mach_absolute_time */
  34. static mach_timebase_info_data_t sTimebaseInfo;
  35. uint64_t rawTime;
  36. uint64_t nanos;
  37. rawTime = mach_absolute_time();
  38. /*
  39. * OS X has a function to convert abs time to nano seconds: AbsoluteToNanoseconds
  40. * However, the function may not be available as we may not have
  41. * access to CoreServices. Because of this, we convert the abs time
  42. * to nano seconds manually.
  43. */
  44. /*
  45. * First grab the time base used on the system, if this is the first
  46. * time we are being called. We can check if the value is uninitialized,
  47. * as the denominator will be zero.
  48. */
  49. if(sTimebaseInfo.denom == 0)
  50. {
  51. (void)mach_timebase_info(&sTimebaseInfo);
  52. }
  53. /*
  54. * Do the conversion. We hope that the multiplication doesn't
  55. * overflow; the price you pay for working in fixed point.
  56. */
  57. nanos = rawTime * sTimebaseInfo.numer / sTimebaseInfo.denom;
  58. /*
  59. * Fill in the timespec container
  60. */
  61. ts->tv_sec = nanos / NANOSECONDS_PER_SECOND;
  62. ts->tv_nsec = nanos - (ts->tv_sec * NANOSECONDS_PER_SECOND);
  63. #else
  64. /*
  65. * As there is no function to fall back onto to get the current
  66. * time, zero out the time so the caller will have a sane value.
  67. */
  68. ts->tv_sec = 0;
  69. ts->tv_nsec = 0;
  70. #endif
  71. return 0;
  72. }