Skip to content

Instantly share code, notes, and snippets.

@alexeiz
Forked from jbenet/current_utc_time.c
Last active October 7, 2015 14:58
Show Gist options
  • Save alexeiz/3182608 to your computer and use it in GitHub Desktop.
Save alexeiz/3182608 to your computer and use it in GitHub Desktop.
workaround for clock_gettime in os x (mach)
#include <time.h>
#include <sys/time.h>
#include <iostream>
#include <ostream>
// POSIX Mach
// clock_gettime clock_get_time
// CLOCK_REALTIME CALENDAR_CLOCK
// CLOCK_MONOTONIC REALTIME_CLOCK
#ifdef __MACH__
#include <mach/clock.h>
#include <mach/mach.h>
timespec 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); // notice mach_task_self as opposed to mach_host_self
timespec ts = {mts.tv_sec, mts.tv_nsec};
return ts;
}
#else
timespec get_time()
{
timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
return ts;
}
#endif
int main()
{
using namespace std;
timespec ts(get_time());
cout << "seconds : " << ts.tv_sec << endl
<< "nanoseconds: " << ts.tv_nsec << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment