Mac doesn't have the Unix clock_gettime
so I am trying to create something that's really portable and only dependent on C.
So far I've come across this function:
static void current_utc_time(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
}
I would like to be able to get seconds and milliseconds for my purposes. This is what I am currently doing and would like some feedback on correctness:
struct timespec requestStart, requestEnd;
current_utc_time(&requestStart);
int i = 0;
while(i < 1000000000)
{
++i;
}
current_utc_time(&requestEnd);
printf("total: ms: %lu\n", (requestStart.tv_nsec - requestEnd.tv_nsec) / (unsigned long)1000000);
This prints out: total: ms: 131
It seems to be correct but I just wanted to make sure before I proceeded. Am I doing my calculations correctly and how can I get the seconds as well as milliseconds?