Skip to content

Instantly share code, notes, and snippets.

@gicmo
Last active December 27, 2015 13:49
Show Gist options
  • Save gicmo/7335930 to your computer and use it in GitHub Desktop.
Save gicmo/7335930 to your computer and use it in GitHub Desktop.
Nanosecond resolution timer code for OSX.
//clang -pedantic -std=c99 -Wall -o nsec_test nsec_test.c && ./nsec_test
#include <assert.h>
#include <mach/mach.h>
#include <mach/mach_time.h>
#include <pthread.h>
// see https://developer.apple.com/library/mac/qa/qa1398/_index.html
typedef uint64_t nano_time_t;
static mach_timebase_info_data_t mtb_;
static void
init_timebase_conv_(void)
{
kern_return_t err;
err = mach_timebase_info(&mtb_);
assert(err == KERN_SUCCESS);
}
nano_time_t
getCurrentTime(void)
{
static pthread_once_t once = PTHREAD_ONCE_INIT;
uint64_t now;
pthread_once(&once, init_timebase_conv_);
now = mach_absolute_time();
return (now * mtb_.numer) / mtb_.denom;
}
#include <stdio.h>
#include <sys/time.h>
int main()
{
uint64_t t1, t2;
struct timeval n1, n2;
t1 = getCurrentTime();
t2 = getCurrentTime();
printf("t1: %llu, t2: %llu [%llu]\n", t1, t2, t2-t1);
gettimeofday(&n1, NULL);
gettimeofday(&n2, NULL);
printf("t1: %d, t2: %d [%d]\n", n1.tv_usec, n2.tv_usec, n2.tv_usec-n2.tv_usec);
return 0;
}
//output
//t1: 146591969850434, t2: 146591969850519 [85]
//t1: 514592, t2: 514592 [0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment