Skip to content

Instantly share code, notes, and snippets.

@xlphs
Created May 22, 2016 16:05
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 xlphs/5ac392361f3981692ca16e4d0b9b6aa0 to your computer and use it in GitHub Desktop.
Save xlphs/5ac392361f3981692ca16e4d0b9b6aa0 to your computer and use it in GitHub Desktop.
#include <time.h>
#include <sys/time.h>
#ifdef __MACH__
#include <mach/clock.h>
#include <mach/mach.h>
#define CLOCK_REALTIME 0
#define CLOCK_MONOTONIC 0
static int
clock_gettime(int clk_id, struct timespec *ts) {
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;
return 0;
}
#endif
void timespec_diff(struct timespec *start, struct timespec *stop,
struct timespec *result)
{
if ((stop->tv_nsec - start->tv_nsec) < 0) {
result->tv_sec = stop->tv_sec - start->tv_sec - 1;
result->tv_nsec = stop->tv_nsec - start->tv_nsec + 1000000000;
} else {
result->tv_sec = stop->tv_sec - start->tv_sec;
result->tv_nsec = stop->tv_nsec - start->tv_nsec;
}
}
timespec ts1, ts2;
clock_gettime(CLOCK_REALTIME, &ts1);
// do something
clock_gettime(CLOCK_REALTIME, &ts2);
timespec diff;
timespec_diff(&ts1, &ts2, &diff);
printf("%lld.%.9ld\n", diff.tv_nsec - diff.tv_nsec);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment