Skip to content

Instantly share code, notes, and snippets.

@schwern
Created March 4, 2016 09:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save schwern/1a4482bfcd5feee0812c to your computer and use it in GitHub Desktop.
Save schwern/1a4482bfcd5feee0812c to your computer and use it in GitHub Desktop.
nanosecond time on OS X
#include <time.h>
#include <stdio.h>
#include <unistd.h>
#ifdef __MACH__
#include <mach/mach_time.h>
#define CLOCK_REALTIME 0
#define CLOCK_MONOTONIC 0
int clock_gettime(int clk_id, struct timespec *t){
mach_timebase_info_data_t timebase;
mach_timebase_info(&timebase);
uint64_t time;
time = mach_absolute_time();
double nseconds = ((double)time * (double)timebase.numer)/((double)timebase.denom);
double seconds = ((double)time * (double)timebase.numer)/((double)timebase.denom * 1e9);
t->tv_sec = seconds;
t->tv_nsec = nseconds;
return 0;
}
#else
#include <time.h>
#endif
int main() {
struct timespec time;
for( int i = 0; i < 10; i++ ) {
clock_gettime(0, &time);
sleep(1);
printf("%ld\n", time.tv_nsec);
}
return 0;
}
/*
$ ./test
310305432132308
310306437356865
310307438458673
310308441630063
310309445567538
310310446334440
310311448553642
310312452901376
310313458078880
310314459376329
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment