#include "timestamp.h"

timespec_t timestamp_now()
{
    timespec_t ts; // tv_sec and tv_nsec fields

    // clock_gettime() version
    {
        clockid_t id = CLOCK_MONOTONIC_RAW;
        int res = clock_gettime(id, &ts);
        if (res != 0)
            printf("clock_gettime() returned an error code! %d\n", res);
    }

    // gettimeofday() version
    //{
    //    struct timeval tv;
    //    gettimeofday (&tv, NULL);

    //    // convert
    //    ts.tv_sec  = tv.tv_sec;
    //    ts.tv_nsec = tv.tv_usec * 1E3;
    //}

    return ts;
}

int32_t get_dt(timespec_t t1, timespec_t t0)
{
    // seconds
    __time_t ds  = t1.tv_sec  - t0.tv_sec;
    // nanoseconds
    long int dns = t1.tv_nsec - t0.tv_nsec;

    // microseconds
    int32_t dt = (ds * 1E6) + (dns * 1E-3);

    printf("%6ds %12dns %12dus     (t1: %6ds %12dns)     (t0: %6ds %12dns)\n",
           ds, dns, dt,
           t1.tv_sec, t1.tv_nsec,
           t0.tv_sec, t0.tv_nsec);

    return dt;
}
