Use clock_gettime on Apple platforms (#35923)

Apple platforms have supported clock_gettime for several years now (since 2016).

Simplify implementation and remove required api call to `mach_absolute_time`.

<!--

If you know who should review your pull request, please assign it to that
person, otherwise the pull request would get assigned randomly.

If your pull request is for a specific language, please add the appropriate
lang label.

-->

Closes #35923

COPYBARA_INTEGRATE_REVIEW=https://github.com/grpc/grpc/pull/35923 from dmaclach:patch-4 45f670d10e
PiperOrigin-RevId: 612965724
pull/35367/merge
dmaclach 1 year ago committed by Copybara-Service
parent 52fc023bae
commit c332854964
  1. 60
      src/core/lib/gpr/posix/time.cc

@ -45,7 +45,6 @@ static struct timespec timespec_from_gpr(gpr_timespec gts) {
return rv; return rv;
} }
#if _POSIX_TIMERS > 0 || defined(__OpenBSD__)
static gpr_timespec gpr_from_timespec(struct timespec ts, static gpr_timespec gpr_from_timespec(struct timespec ts,
gpr_clock_type clock_type) { gpr_clock_type clock_type) {
// //
@ -83,65 +82,6 @@ static gpr_timespec now_impl(gpr_clock_type clock_type) {
return gpr_from_timespec(now, clock_type); return gpr_from_timespec(now, clock_type);
} }
} }
#else
// For some reason Apple's OSes haven't implemented clock_gettime.
#include <mach/mach.h>
#include <mach/mach_time.h>
#include <sys/time.h>
static double g_time_scale = []() {
mach_timebase_info_data_t tb = {0, 1};
mach_timebase_info(&tb);
return static_cast<double>(tb.numer) / static_cast<double>(tb.denom);
}();
static uint64_t g_time_start = mach_absolute_time();
void gpr_time_init(void) { gpr_precise_clock_init(); }
static gpr_timespec now_impl(gpr_clock_type clock) {
gpr_timespec now;
struct timeval now_tv;
double now_dbl;
now.clock_type = clock;
switch (clock) {
case GPR_CLOCK_REALTIME:
// gettimeofday(...) function may return with a value whose tv_usec is
// greater than 1e6 on iOS The case is resolved with the guard at end of
// this function.
gettimeofday(&now_tv, nullptr);
now.tv_sec = now_tv.tv_sec;
now.tv_nsec = now_tv.tv_usec * 1000;
break;
case GPR_CLOCK_MONOTONIC:
// Add 5 seconds arbitrarily: avoids weird conditions in gprpp/time.cc
// when there's a small number of seconds returned.
now_dbl = 5.0e9 +
((double)(mach_absolute_time() - g_time_start)) * g_time_scale;
now.tv_sec = (int64_t)(now_dbl * 1e-9);
now.tv_nsec = (int32_t)(now_dbl - ((double)now.tv_sec) * 1e9);
break;
case GPR_CLOCK_PRECISE:
gpr_precise_clock_now(&now);
break;
case GPR_TIMESPAN:
abort();
}
// Guard the tv_nsec field in valid range for all clock types
while (GPR_UNLIKELY(now.tv_nsec >= 1e9)) {
now.tv_sec++;
now.tv_nsec -= 1e9;
}
while (GPR_UNLIKELY(now.tv_nsec < 0)) {
now.tv_sec--;
now.tv_nsec += 1e9;
}
return now;
}
#endif
gpr_timespec (*gpr_now_impl)(gpr_clock_type clock_type) = now_impl; gpr_timespec (*gpr_now_impl)(gpr_clock_type clock_type) = now_impl;

Loading…
Cancel
Save