【发布时间】:2020-10-10 17:17:50
【问题描述】:
我想编写一个小循环,以这种格式 [hh:mm:ss:msms] 打印时间戳。最好的情况是这样做的单独功能。感谢您的回复
【问题讨论】:
标签: c++ time timestamp unix-timestamp
我想编写一个小循环,以这种格式 [hh:mm:ss:msms] 打印时间戳。最好的情况是这样做的单独功能。感谢您的回复
【问题讨论】:
标签: c++ time timestamp unix-timestamp
如果你想要那种特定的格式,我知道的唯一方法是自己解析自纪元计数器以来的时间(或者获取默认时间格式,如下所示,解析其所有元素并自己在另一个字符串中重新排列它们) .
同时,您可以像这样使用默认格式(包括 ctime 和 chrono)
auto t = std::chrono::system_clock::now();
auto ptr = std::chrono::system_clock::to_time_t(t);
char time[255];
auto frm = ctime_s(time, 255, &ptr);
printf("%s\n", time);
getchar();
输出:
Sat Jun 20 07:28:36 2020
编辑:
我找到了一种使用标准函数的方法:
char timestamp[50]{ 0 };
std::time_t time = std::time(nullptr);
std::strftime(timestamp, 30, "[%H:%M:%S]", std::localtime(&time));
不幸的是,我不相信有一个标准的方法来获取当前的毫秒数,可能是因为操作系统没有跟踪它。
当你在其他人的程序中看到时间戳时,毫秒计数很可能是他们自己计算的(但我可能错了)。
如果您想这样做,您可以在程序开始时获取毫秒数(自纪元或自操作系统启动以来,取决于您使用的函数),然后每次计算时间戳时,再次获取它并从中减去原来的那个。
假设你使用 Windows,你可以这样做:
// Get the initial tick
unsigned int starttick = GetTickCount();
... Do your stuff here
// Get the current tick:
unsigned int stoptick = GetTickCount();
// Subtract current tick from start tick to get elapsed milliseconds (roughly)
printf("%d", (stoptick - starttick));
或者您可以使用 Chrono:
auto s = std::chrono::high_resolution_clock::now();
Sleep(1500);
auto st = std::chrono::high_resolution_clock::now();
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(st - s).count();
printf("%lld", ms);
getchar();
【讨论】: