Skip to content

Instantly share code, notes, and snippets.

@otoolep
Forked from jbenet/current_utc_time.c
Created June 17, 2014 22:00
  • Select an option

Select an option

Revisions

  1. @invalid-email-address Anonymous created this gist Jul 17, 2011.
    43 changes: 43 additions & 0 deletions current_utc_time.c
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    /*
    author: jbenet
    os x, compile with: gcc -o testo test.c
    linux, compile with: gcc -o testo test.c -lrt
    */

    #include <time.h>
    #include <sys/time.h>
    #include <stdio.h>

    #ifdef __MACH__
    #include <mach/clock.h>
    #include <mach/mach.h>
    #endif


    void current_utc_time(struct timespec *ts) {

    #ifdef __MACH__ // OS X does not have clock_gettime, use clock_get_time
    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;
    #else
    clock_gettime(CLOCK_REALTIME, ts);
    #endif

    }


    int main(int argc, char **argv) {

    struct timespec ts;
    current_utc_time(&ts);

    printf("s: %lu\n", ts.tv_sec);
    printf("ns: %lu\n", ts.tv_nsec);
    return 0;

    }