clock_gettime alternative in Mac OS X

Delan Azabani picture Delan Azabani · Mar 2, 2011 · Viewed 93.2k times · Source

When compiling a program I wrote on Mac OS X after installing the necessary libraries through MacPorts, I get this error:

In function 'nanotime':
error: 'CLOCK_REALTIME' undeclared (first use in this function)
error: (Each undeclared identifier is reported only once
error: for each function it appears in.)

It appears that clock_gettime is not implemented in Mac OS X. Is there an alternative means of getting the epoch time in nanoseconds? Unfortunately gettimeofday is in microseconds.

Answer

jbenet picture jbenet · Jul 17, 2011

After hours of perusing different answers, blogs, and headers, I found a portable way to get the current time:

#include <time.h>
#include <sys/time.h>

#ifdef __MACH__
#include <mach/clock.h>
#include <mach/mach.h>
#endif



struct timespec ts;

#ifdef __MACH__ // OS X does not have clock_gettime, use clock_get_time
clock_serv_t cclock;
mach_timespec_t mts;
host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
clock_get_time(cclock, &mts);
mach_port_deallocate(mach_task_self(), cclock);
ts.tv_sec = mts.tv_sec;
ts.tv_nsec = mts.tv_nsec;

#else
clock_gettime(CLOCK_REALTIME, &ts);
#endif

or check out this gist: https://gist.github.com/1087739

Hope this saves someone time. Cheers!