c / c ++微秒时间戳 [英] c/c++ microsecond timestamp

查看:222
本文介绍了c / c ++微秒时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用这段代码在c / c ++中获取微秒的时间戳。但它看起来不像微秒。也不知道是否有任何方式来格式化。

I used this piece of code to get timestamp in microsecond in c/c++. but it doesn't look like microsecond. also i don't know if there is any way to format it.

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

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

and what is the right format to output it? Thank you!

推荐答案

次秒级的典型打印格式使用小数指示符(在许多地方),所以59,一些秒可能看起来像59.00013。

The typical printing format for sub-second times uses the decimal indicator (. in many locales) and so 59 and some seconds might look like 59.00013.

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

The micro variable you created takes the current microsecond count, multiplies it by 1000000 then adds the current microsecond count again; I expect that you intend to either use the microsecond count alone, or together with the count of seconds:

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

应写为

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

以相同的数字一起获取秒和微秒。

to get seconds and microseconds together in the same number.

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

To write this into your output, you might consider changing the line

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

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

使用改变的 micro 也输出

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

这篇关于c / c ++微秒时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆