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

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

问题描述

我用这块code,以获得时间戳在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.

微<​​/ code>创建变量采用电流微秒数,乘以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);

使用修改微<​​/ code>定义,你也可以输出

Using the altered micro definition, you can also output

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

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

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