C++ chrono系统时间以毫秒为单位,时间运算
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9089842/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ chrono system time in milliseconds, time operations
提问by Dejwi
I've got a small problem caused by insufficient documentation of C++11.
由于 C++11 的文档不足,我遇到了一个小问题。
I'd like to obtain a time since epoch in milliseconds, or nanoseconds or seconds and then I will have to "cast" this value to another resolution. I can do it using gettimeofday() but it will be to easy, so I tried to achieve it using std::chrono.
我想以毫秒、纳秒或秒为单位获得自纪元以来的时间,然后我必须将此值“转换”为另一个分辨率。我可以使用 gettimeofday() 来完成它,但它会很容易,所以我尝试使用 std::chrono 来实现它。
I tried:
我试过:
std::chrono::time_point<std::chrono::system_clock> now =
std::chrono::system_clock::now();
But I have no idea what is a resolution of obtained in this way time_point, and I don't know how to get this time as a simple unsigned long long, and I haven't any conception how to cast it to another resolution.
但是我不知道以这种方式获得的 time_point 的分辨率是什么,我不知道如何将这个时间作为一个简单的 unsigned long long 获得,并且我没有任何概念如何将其转换为另一个分辨率。
回答by R. Martinho Fernandes
You can do now.time_since_epoch()
to get a duration representing the time since the epoch, with the clock's resolution. To convert to milliseconds use duration_cast
:
您可以now.time_since_epoch()
使用时钟的分辨率来获取表示自纪元以来时间的持续时间。要转换为毫秒,请使用duration_cast
:
auto duration = now.time_since_epoch();
auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();