2

我使用这段代码在 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);

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

4

4 回答 4

4

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

using std::chrono;
__int64 microseconds_since_epoch = duration_cast<microseconds>(system_clock::now().time_since_epoch()).count();
于 2017-09-28T02:14:51.383 回答
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);
于 2014-03-05T16:34:05.497 回答
2

使用Howard Hinnant 的免费、开源、仅标题的日期/时间库

#include "date/date.h"
#include <iostream>

int
main()
{
    using namespace date;
    using namespace std;
    using namespace std::chrono;
    cout << floor<microseconds>(system_clock::now()) << '\n';
}

这只是为我输出:

2017-09-29 15:46:27.793195
于 2017-09-29T15:48:51.047 回答
0

如果您使用 Visual Studio(Windows 环境),
如何使用 WINDOWS API:GetLocalTime()

  char* lptszBuffer = new char[100]; 
  SYSTEMTIME sysTime;
  GetLocalTime( &sysTime );
  sprintf_s(lptszBuffer, 100, "[%02d:%02d:%02d.%03d]", sysTime.wHour, sysTime.wMinute, sysTime.wSecond, sysTime.wMilliseconds);

结果格式:[11:27:00.027]

于 2019-03-13T02:34:56.180 回答