Skip to content

Instantly share code, notes, and snippets.

Last active November 30, 2022 06:45
  • Star 16 You must be signed in to star a gist
  • Fork 3 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?
#include "mach_gettime.h"
#include <mach/mach_time.h>
#define MT_NANO (+1.0E-9)
#define MT_GIGA UINT64_C(1000000000)
// TODO create a list of timers,
static double mt_timebase = 0.0;
static uint64_t mt_timestart = 0;
int clock_gettime(clockid_t clk_id, struct timespec *tp)
kern_return_t retval = KERN_SUCCESS;
if( clk_id == TIMER_ABSTIME) {
if (!mt_timestart) { // only one timer, initilized on the first call to the TIMER
mach_timebase_info_data_t tb = { 0 };
mt_timebase = tb.numer;
mt_timebase /= tb.denom;
mt_timestart = mach_absolute_time();
double diff = (mach_absolute_time() - mt_timestart) * mt_timebase;
tp->tv_sec = diff * MT_NANO;
tp->tv_nsec = diff - (tp->tv_sec * MT_GIGA);
else { // other clk_ids are mapped to the coresponding mach clock_service
clock_serv_t cclock;
mach_timespec_t mts;
host_get_clock_service(mach_host_self(), clk_id, &cclock);
retval = clock_get_time(cclock, &mts);
mach_port_deallocate(mach_task_self(), cclock);
tp->tv_sec = mts.tv_sec;
tp->tv_nsec = mts.tv_nsec;
return retval;
/* Copyright (c) 2015-2018 Alf Watt - Open Source - */
#include <sys/types.h>
#include <sys/_types/_timespec.h>
#include <mach/mach.h>
#include <mach/clock.h>
#ifndef mach_time_h
#define mach_time_h
/* The opengroup spec isn't clear on the mapping from REALTIME to CALENDAR
being appropriate or not. */
// XXX only supports a single timer
#define TIMER_ABSTIME -1
typedef int clockid_t;
/* the mach kernel uses struct mach_timespec, so struct timespec
is loaded from <sys/_types/_timespec.h> for compatability */
// struct timespec { time_t tv_sec; long tv_nsec; };
int clock_gettime(clockid_t clk_id, struct timespec *tp);
/* Copyright (c) 2015-2018 Alf Watt - Open Source - */
Copy link

Thanks. It looks like somewhat complete version.

Copy link

st3fan commented Mar 13, 2017

Hi @alfwatt thank you for this implementation. I'd like to use your code in my project. Would you mind letting me know if that is ok or please put a license on top of this gist? (I'm using MIT for my code)

Copy link

alfwatt commented Mar 15, 2018

Apologies for the delay, MIT License applied:

Copy link

Hi, @alfwatt I need your help please.
I have an @imac mid 2009. Every time I ran vagrant, get the clock_gettime error, I fairly new t programming, I ned you to guide me where exactly I have to put this code at for it to work. Thank you. email >

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