c - 自纪元以来的打印时间(以纳秒为单位)

标签 c time epoch

所以我知道如何以秒为单位打印自纪元以来的时间,显然甚至以毫秒为单位,但是当我尝试以纳秒为单位时,我总是得到一个太小的整数的虚假输出,并且它有时打印的数字小于上次运行的数字。

#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 纳秒。

如能提供正确显示的任何帮助,我们将不胜感激。

最佳答案

纳秒部分只是“小数”部分,您还必须加上秒。

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

关于c - 自纪元以来的打印时间(以纳秒为单位),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54763262/

相关文章:

iphone - 您如何将时间用作核心图图中的轴?

c - 奇怪的 malloc 访问错误

python - 将 OpenGL 模型导出为 .OBJ

time - 将 <integer> 秒添加到 PostgreSQL 中的 <timestamp>

matlab - 如何在 MATLAB 中从纪元时间获取秒数?

Java,将纪元转换为毫秒

函数调用中未填充 C 字符串

c - Jaccard距离在C中的实现

ruby-on-rails - (Rails)测试在深夜失败

go - 如何在 go 中使用 time.Parse() 逗号分隔毫秒