c/c 微秒时间戳

新手上路,请多包涵

我使用这段代码在 c/c++ 中以微秒为单位获取时间戳。但它看起来不像微秒。我也不知道有没有办法格式化。

 timeval curTime;
gettimeofday(&curTime, NULL);
int milli = curTime.tv_usec / 1000;
unsigned long micro = curTime.tv_usec*(uint64_t)1000000+curTime.tv_usec;

char buffer [80];
//localtime is not thread safe
strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", localtime(&curTime.tv_sec));

char currentTime[84] = "";
char currentTime2[80] = "";
sprintf(currentTime, "%s:%3d", buffer, milli);
sprintf(currentTime2, "%s:%Lu", buffer, micro);
printf("time %s, hptime %s\n", currentTime, currentTime2);

什么是正确的输出格式?谢谢!

原文由 bbc 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 668
2 个回答

亚秒级时间的典型打印格式使用十进制指示符(在许多语言环境中为 . ),因此 59 和某些秒可能看起来像 59.00013。

您创建的 micro 变量采用当前微秒计数,将其乘以 1000000,然后再次添加当前微秒计数;我希望您打算单独使用微秒计数,或者与秒计数一起使用:

 unsigned long micro = curTime.tv_usec*(uint64_t)1000000+curTime.tv_usec;

应该写成

unsigned long micro = curTime.tv_sec*(uint64_t)1000000+curTime.tv_usec;

以相同的数字获得秒和微秒。

要将其写入您的输出,您可以考虑更改行

sprintf(currentTime2, "%s:%Lu", buffer, micro);

sprintf(currentTime2, "%s.%Lu", buffer, curTime.tv_usec);

使用修改后的 micro 定义,也可以输出

sprintf(currentSeconds, "%.6f", micro / 1000000);

原文由 abiessu 发布,翻译遵循 CC BY-SA 3.0 许可协议

一些更短的尝试(C++):

 using namespace std::chrono;
__int64 microseconds_since_epoch = duration_cast<microseconds>(system_clock::now().time_since_epoch()).count();

原文由 Lorien Brune 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题