Skip to content

Instantly share code, notes, and snippets.

@JanSimek
Created May 19, 2014 20:40
Show Gist options
  • Save JanSimek/1ff92b3221bff633fcd4 to your computer and use it in GitHub Desktop.
Save JanSimek/1ff92b3221bff633fcd4 to your computer and use it in GitHub Desktop.
clock_gettime reimplementation on OS X
// posix_public.h
#ifdef __APPLE__
enum clk_id_t { CLOCK_REALTIME, CLOCK_MONOTONIC, CLOCK_MONOTONIC_RAW };
int clock_gettime(clk_id_t clock, struct timespec *tp);
#endif
// posix_main.cpp
#ifdef __APPLE__
// OS X doesn't have clock_gettime()
int clock_gettime(clk_id_t clock, struct timespec *tp)
{
switch(clock)
{
case CLOCK_MONOTONIC_RAW:
case CLOCK_MONOTONIC:
{
clock_serv_t clock_ref;
mach_timespec_t tm;
host_name_port_t self = mach_host_self();
memset(&tm, 0, sizeof(tm));
if (KERN_SUCCESS != host_get_clock_service(self, SYSTEM_CLOCK, &clock_ref))
{
return -1;
}
if (KERN_SUCCESS != clock_get_time(clock_ref, &tm))
{
mach_port_deallocate(mach_task_self(), self);
return -1;
}
mach_port_deallocate(mach_task_self(), self);
mach_port_deallocate(mach_task_self(), clock_ref);
tp->tv_sec = tm.tv_sec;
tp->tv_nsec = tm.tv_nsec;
break;
}
case CLOCK_REALTIME:
default:
{
struct timeval now;
if (KERN_SUCCESS != gettimeofday(&now, NULL))
{
return -1;
}
tp->tv_sec = now.tv_sec;
tp->tv_nsec = now.tv_usec * 1000;
break;
}
}
return 0;
}
#endif // __APPLE__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment