Showing entries with tag "epoch".

Found 2 entries

C: Nanoseconds since Unix epoch

I needed a function to use as a simple seed for srand(). Unixtime in nanoseconds changes very frequently and serves as a semi-decent random seed.

#include <time.h> // for clock_gettime()

// Nanoseconds since Unix epoch
uint64_t nanos() {
    struct timespec ts;

    // int8_t ok = clock_gettime(CLOCK_MONOTONIC, &ts); // Uptime
    int8_t ok = clock_gettime(CLOCK_REALTIME, &ts);  // Since epoch

    if (ok != 0) {
        return 0; // Return 0 on failure (you can handle this differently)
    }

    // Calculate nanoseconds
    uint64_t ret = (uint64_t)ts.tv_sec * 1000000000ULL + (uint64_t)ts.tv_nsec;

    return ret;
}

See also: Microseconds since epoch in Perl

Leave A Reply

Perl: Get microseconds since Unix epoch

I need to get system uptime with a higher resolution that just one second. This is the function I came up with to return uptime in microseconds.

sub micros {
    require Time::HiRes;

    my @p   = Time::HiRes::gettimeofday();
    my $ret = ($p[0] * 1000000) + $p[1];

    return $ret;
}
Leave A Reply