我使用这段代码在 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 许可协议
亚秒级时间的典型打印格式使用十进制指示符(在许多语言环境中为
.
),因此 59 和某些秒可能看起来像 59.00013。您创建的
micro
变量采用当前微秒计数,将其乘以 1000000,然后再次添加当前微秒计数;我希望您打算单独使用微秒计数,或者与秒计数一起使用:应该写成
以相同的数字获得秒和微秒。
要将其写入您的输出,您可以考虑更改行
至
使用修改后的
micro
定义,也可以输出