问题描述
如何获得(使用 std::chrono 库)以毫秒为单位的两个时间点之间的差异?
How can I get (using the std::chrono library) the difference between two points in time in milliseconds?
我可以用这个:
std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now();
std::chrono::time_point<std::chrono::system_clock> foo = now + std::chrono::milliseconds(100);
std::chrono::duration<float> difference = foo - now;
const int milliseconds = difference.count() * 1000;
如何以毫秒为单位获得这个时间,以便我可以将持续时间用作无符号整数,而不是浮点数,然后乘以 1000?
推荐答案
std::chrono::duration
有两个模板参数,第二个就是度量单位.您可以调用 std::chrono::duration_cast
从一种持续时间类型转换为另一种持续时间类型.此外,还有一个预定义的毫秒持续时间类型:std::chrono::milliseconds
.将其组合在一起:
std::chrono::duration
has two template parameters, the second being exactly the unit of measure. You can invoke std::chrono::duration_cast
to cast from one duration type to another. Also, there is a predefined duration type for milliseconds: std::chrono::milliseconds
. Composing this together:
auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(foo - now);
要获得实际的毫秒数,请使用 duration::count
:
To get the actual number of milliseconds, use duration::count
:
auto ms = milliseconds.count();
它的返回类型是 duration::rep
,对于像 std::chrono::milliseconds
这样的标准持续时间类型,它是一个未指定大小的有符号整数.
Its return type is duration::rep
, which for standard duration types like std::chrono::milliseconds
is a signed integer of unspecified size.
这篇关于Chrono - 以毫秒为单位的两个时间点之间的差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!