WolvenOmega WolvenOmega - 2 months ago 13
C Question

Printing Time since Epoch in Nanoseconds

So I know how to print time since epoch in seconds, and evidently even milliseconds, but when I try nanoseconds I keep getting bogus output of an integer that's way too small, and it sometimes prints numbers smaller than the last run.

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

int main (void)
{
long int ns;
struct timespec spec;

clock_gettime(CLOCK_REALTIME, &spec);
ns = spec.tv_nsec;;

printf("Current time: %ld nonoseconds since the Epoch\n", ns);
return 0;
}


For instance, with a run from this I got 35071471 nanoseconds since epoch.

Any help with getting this to display correctly would be appreciated.

Answer

The nanosecond part is just the "fractional" part, you have to add the seconds, too.

// otherwise gcc with option -std=c11 complaints
#define _POSIX_C_SOURCE 199309L
#include <stdio.h>
#include <time.h>
#include <stdint.h>
#include <inttypes.h>
#define BILLION  1000000000L
int main(void)
{
  long int ns;
  uint64_t all;
  time_t sec;
  struct timespec spec;

  clock_gettime(CLOCK_REALTIME, &spec);
  sec = spec.tv_sec;
  ns = spec.tv_nsec;

  all = (uint64_t) sec * BILLION + (uint64_t) ns;

  printf("Current time: %" PRIu64  " nanoseconds since the Epoch\n", all);
  return 0;
}
Comments