shithub: femtolisp

ref: 79bb6bfb032a4cd74bdbaf99d46a304d80506c46
dir: /llt/timefuncs.c/

View raw version
#define _XOPEN_SOURCE 600
#include "platform.h"

#if defined(__plan9__)
double floattime(void)
{
    return (double)nsec() / 1.0e9;
}
#else
double tv2float(struct timeval *tv)
{
    return (double)tv->tv_sec + (double)tv->tv_usec/1.0e6;
}

double diff_time(struct timeval *tv1, struct timeval *tv2)
{
    return tv2float(tv1) - tv2float(tv2);
}
#endif

// return as many bits of system randomness as we can get our hands on
uint64_t i64time(void)
{
    uint64_t a;
#if defined(__plan9__)
    a = nsec();
#else
    struct timeval now;
    gettimeofday(&now, NULL);
    a = (((uint64_t)now.tv_sec)<<32) + (uint64_t)now.tv_usec;
#endif

    return a;
}

double clock_now(void)
{
#if defined(__plan9__)
    return floattime();
#else
    struct timeval now;

    gettimeofday(&now, NULL);
    return tv2float(&now);
#endif
}

void timestring(double seconds, char *buffer, size_t len)
{
#if defined(__plan9__)
    Tm tm;
    snprint(buffer, len, "%τ", tmfmt(tmtime(&tm, seconds, tzload("local")), nil));
#else
    time_t tme = (time_t)seconds;

    char *fmt = "%c"; /* needed to suppress GCC warning */
    struct tm tm;

    localtime_r(&tme, &tm);
    strftime(buffer, len, fmt, &tm);
#endif
}

#if defined(__plan9__)
double parsetime(const char *str)
{
    Tm tm;

    if (tmparse(&tm, "?WWW, ?MM ?DD hh:mm:ss ?Z YYYY", str, tzload("local"), nil) == nil)
        return -1;

    return tmnorm(&tm);
}
#else
double parsetime(const char *str)
{
    char *fmt = "%c"; /* needed to suppress GCC warning */
    char *res;
    time_t t;
    struct tm tm;

    res = strptime(str, fmt, &tm);
    if (res != NULL) {
        tm.tm_isdst = -1; /* Not set by strptime(); tells mktime() to determine
                            whether daylight saving time is in effect */
        t = mktime(&tm);
        if (t == ((time_t)-1))
            return -1;
        return (double)t;
    }
    return -1;
}
#endif

void sleep_ms(int ms)
{
    if (ms == 0)
        return;

#if defined(__plan9__)
    sleep(ms);
#else
    struct timeval timeout;

    timeout.tv_sec = ms/1000;
    timeout.tv_usec = (ms % 1000) * 1000;
    select(0, NULL, NULL, NULL, &timeout);
#endif
}