Skip to content

Instantly share code, notes, and snippets.

Created July 17, 2011 16:17
  • Star 87 You must be signed in to star a gist
  • Fork 24 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
work around lack of clock_gettime in os x
author: jbenet
os x, compile with: gcc -o testo test.c
linux, compile with: gcc -o testo test.c -lrt
#include <time.h>
#include <sys/time.h>
#include <stdio.h>
#ifdef __MACH__
#include <mach/clock.h>
#include <mach/mach.h>
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;
clock_gettime(CLOCK_REALTIME, ts);
int main(int argc, char **argv) {
struct timespec ts;
printf("s: %lu\n", ts.tv_sec);
printf("ns: %lu\n", ts.tv_nsec);
return 0;
Copy link

MacDada commented Jan 23, 2014

thx, it works! ;-)

Copy link


Copy link

I really appreciate it.

Copy link


Copy link

wujun commented Feb 3, 2015

thanks your code, thanks

Copy link


Copy link

Awesome! Thanks

Copy link

alfwatt commented Aug 4, 2015

Copy link

matrumz commented Nov 17, 2015

Many thanks. My senior project is that much closer to completion!

Copy link

thanks for sharing,appreciate it.

Copy link

I need the return value in clock_get_time(..), how can it be done os OS X?
For details please see

Copy link

aczzdx commented Nov 14, 2017

Thanks for sharing. This code helps me a lot.

Copy link

This very useful.
Thank you.

Copy link

Nice code. Is this code under a license?
Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment