如何在当前时间的打印输出中获得更高的精度(几分之一秒)? [英] How to get higher precision (fractions of a second) in a printout of current time?
问题描述
我尝试了几种从 system_clock
打印时间的方法,但我不能得到除整秒之外的任何东西:
I've tried a couple methods to print out time from the system_clock
but I can't get anything other than whole seconds:
system_clock::time_point now = system_clock::now();
std::time_t now_c = system_clock::to_time_t(now);
std::cout<<ctime(&now_c);
std::cout<<std::put_time(std::localtime(&now_c), "%T")<<" ";
now()
高精度数据,或者我只是找不到提取打印信息的功能?
Does the now()
function actually hold high precision data, or is that I just can't find the function that extracts that information for printing?
注意:我不是要计算时间间隔。我想要几分之一秒的当前时间,并通过 cout
打印出来。我只是找不到一个办法做到这一点。
Note: I am not looking to calculate a time interval. I want the current time with fractions of a second, and to print it out via cout
. I just can't find a way to do this.
我知道 std :: chrono :: high_resolution_clock
,但也没有办法打印出它的 now()
。此外, setprecision
函数对 put_time
或 ctime $
And I know about std::chrono::high_resolution_clock
but also see no way to print out its now()
. Additionally, the setprecision
function has no effect on the output of put_time
or ctime
.
推荐答案
我已经得到了没有解决这个问题的答案。解决方案
您可以执行以下操作:
#include <chrono>
#include <ctime>
#include <iostream>
#include <string>
std::string GetLocalTime() {
auto now(std::chrono::system_clock::now());
auto seconds_since_epoch(
std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()));
// Construct time_t using 'seconds_since_epoch' rather than 'now' since it is
// implementation-defined whether the value is rounded or truncated.
std::time_t now_t(
std::chrono::system_clock::to_time_t(
std::chrono::system_clock::time_point(seconds_since_epoch)));
char temp[10];
if (!std::strftime(temp, 10, "%H:%M:%S.", std::localtime(&now_t)))
return "";
return std::string(temp) +
std::to_string((now.time_since_epoch() - seconds_since_epoch).count());
}
int main() {
std::cout << GetLocalTime() << '\n';
return 0;
}
这篇关于如何在当前时间的打印输出中获得更高的精度(几分之一秒)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!