自纳时代以来的印刷时间

时间:2016-09-11 18:23:15

标签: c time epoch

所以我知道如何以秒为单位打印时间,显然甚至是几毫秒,但是当我尝试纳秒时,我不断得到一个整数太小的虚假输出,它有时打印的数字比上次运行的数字小。 / p>

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

例如,从此开始,我从纪元开始就得到了35071471纳秒。

任何有关正确显示此内容的帮助都将不胜感激。

1 个答案:

答案 0 :(得分:4)

纳秒部分只是&#34;分数&#34;部分,您还必须添加秒数。

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