Showing entries with tag "uptime".

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

Perlfunc: get_uptime()

Simple code to get the current uptime in days.

sub get_uptime {
   open(FILE,'/proc/uptime');
   my $line = <FILE>;
   close FILE;

   # The first value is seconds of uptime, not sure about the second
   my ($seconds,$foo) = split(/\s+/,$line);

   # Convert seconds to days
   my $ret = int($seconds / (3600 * 24));

   return $ret;
}
Leave A Reply