[英]What precision is used by std::chrono::system_clock?
Here's some code that I found:这是我找到的一些代码:
std::cout << std::chrono::system_clock::now().time_since_epoch().count() << std::endl;
This prints 1662563612364838407
for me;这为我打印
1662563612364838407
; so it looks like this prints the number of nanoseconds since the UNIX epoch (1970-01-01).所以看起来这打印了自 UNIX 时代(1970-01-01)以来的纳秒数。
But is this precision guaranteed?但是这种精度能保证吗? I didn't find any indication at https://en.cppreference.com/w/cpp/chrono/system_clock that this value will always be in nanoseconds.
我在https://en.cppreference.com/w/cpp/chrono/system_clock没有发现任何迹象表明该值始终以纳秒为单位。 Is it possible that this will return eg microseconds with another compiler, operating system or hardware?
是否有可能这将返回例如微秒与另一个编译器、操作系统或硬件?
No it is not guaranteed.不,不能保证。 You can use the clocks
period
member alias to get tick period in seconds:您可以使用时钟
period
成员别名以秒为单位获取滴答周期:
#include <chrono>
#include <iostream>
int main() {
std::cout << std::chrono::system_clock::period::num << " / " << std::chrono::system_clock::period::den;
}
Possible output:可能的 output:
1 / 1000000000
Is it possible that this will return eg microseconds with another compiler, operating system or hardware?
是否有可能这将返回例如微秒与另一个编译器、操作系统或硬件?
Yes, but you can alwaysstd::chrono::duration_cast
it into a known duration unit.是的,但是您始终可以将其
std::chrono::duration_cast
转换为已知的持续时间单位。 If you want it in seconds for example:如果你想在几秒钟内得到它,例如:
auto dur = std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::system_clock::now().time_since_epoch());
std::cout << dur << '\n';
Possible output:可能的 output:
1662575635s
Pre C++20:预 C++20:
std::cout << dur.count() << '\n';
1662575635
Note: Stay within the chrono
domain until it's absolutely necessary to leave it (using .count()
etc).注意:保持在
chrono
域中,直到绝对有必要离开它(使用.count()
等)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.