Created
March 4, 2016 09:37
-
-
Save schwern/1a4482bfcd5feee0812c to your computer and use it in GitHub Desktop.
nanosecond time on OS X
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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