Printing Time since Epoch in Nanoseconds

前端 未结 1 1333
無奈伤痛
無奈伤痛 2021-01-13 17:58

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 sma

相关标签:
1条回答
  • 2021-01-13 18:48

    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;
    }
    
    0 讨论(0)
提交回复
热议问题