Printing Time since Epoch in Nanoseconds

强颜欢笑 提交于 2019-12-01 04:45:52

问题


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.


回答1:


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;
}


来源:https://stackoverflow.com/questions/39439268/printing-time-since-epoch-in-nanoseconds

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!