39 #if !defined(HAVE_CLOCK_GETTIME) && defined HAVE_CLOCK_GET_TIME
40 #include <mach/clock.h>
41 #include <mach/mach.h>
66 const char *
ctimespec_r(
const struct timespec *tp,
char *buf,
size_t size,
74 localtime_r(&tp->tv_sec, &tm);
77 size_t len = strftime(buf, size,
"%F-%T", &tm);
81 snprintf(buf+len, size-len,
".%09ld", tp->tv_nsec);
86 const char *
ctimespec(
const struct timespec *tp,
bool ns)
95 double time_diff(
const struct timespec *tp1,
const struct timespec *tp2)
97 return (
double) (tp2->tv_sec - tp1->tv_sec)
98 + (
double) (tp2->tv_nsec - tp1->tv_nsec) / (
long)
NSEC_PER_SEC;
106 return (
double) (now.tv_sec - tp->tv_sec)
107 + (
double) (now.tv_nsec - tp->tv_nsec) / (
long)
NSEC_PER_SEC;
112 if (tp1->tv_sec > tp2->tv_sec)
114 if (tp1->tv_sec < tp2->tv_sec)
116 return tp1->tv_nsec > tp2->tv_nsec;
121 bool normalized =
true;
128 while (tp->tv_nsec < 0) {
138 tp->tv_sec += (time_t) seconds;
139 tp->tv_nsec += (long) ((seconds - (time_t) seconds) * (
long)
NSEC_PER_SEC);
144 #if defined HAVE_CLOCK_GETTIME
147 static struct timespec res = {.tv_sec = 0, .tv_nsec = 0};
150 if (!res.tv_sec && !res.tv_nsec) {
151 clock_getres(CLOCK_REALTIME, &res);
153 assert(res.tv_nsec == 1);
157 return clock_gettime(CLOCK_REALTIME, tp);
160 #elif defined HAVE_CLOCK_GET_TIME
161 int gettime(
struct timespec *tp)
163 static struct timespec res = {.tv_sec = 0, .tv_nsec = 0};
166 host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
169 if (!res.tv_sec && !res.tv_nsec) {
170 natural_t attribute[4];
171 mach_msg_type_number_t count =
sizeof(attribute)/
sizeof(natural_t);
172 clock_get_attributes(cclock, CLOCK_GET_TIME_RES,
173 (clock_attr_t) &attribute, &count);
175 assert(attribute[0] > 1);
179 kern_return_t rc = clock_get_time(cclock, &mts);
180 mach_port_deallocate(mach_task_self(), cclock);
182 tp->tv_sec = mts.tv_sec;
183 tp->tv_nsec = mts.tv_nsec;
185 return (rc == KERN_SUCCESS ? 0 : -1);