[英]Chrono - The difference between two points in time in milliseconds?
How can I get (using the std::chrono library) the difference between two points in time in milliseconds? 我怎样才能(使用std :: chrono库)获得两个时间点之间的差异(以毫秒为单位)?
I could do that using this: 我可以用这个来做到这一点:
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;
How can I get this time in milliseconds, so I can use the duration as a unsigned int, and not a float and then multiply by 1000? 我怎样才能在毫秒内得到这个时间,所以我可以将持续时间用作unsigned int,而不是float,然后乘以1000?
std::chrono::duration
has two template parameters, the second being exactly the unit of measure. std::chrono::duration
有两个模板参数,第二个是度量单位。 You can invoke std::chrono::duration_cast
to cast from one duration type to another. 您可以调用
std::chrono::duration_cast
从一种持续时间类型转换为另一种持续时间类型。 Also, there is a predefined duration type for milliseconds: std::chrono::milliseconds
. 此外,还有一个预定义的持续时间类型,为毫秒:
std::chrono::milliseconds
。 Composing this together: 一起撰写:
auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(foo - now);
To get the actual number of milliseconds, use duration::count
: 要获得实际的毫秒数,请使用
duration::count
:
auto ms = milliseconds.count();
Its return type is duration::rep
, which for standard duration types like std::chrono::milliseconds
is a signed integer of unspecified size. 它的返回类型是
duration::rep
,对于标准持续时间类型,如std::chrono::milliseconds
是一个未指定大小的有符号整数。
chrono::duration_cast<chrono::milliseconds>(end_time - start_time).count()
http://www.cplusplus.com/reference/chrono/duration_cast/
std::chrono::duration_cast<std::chrono::milliseconds>();
I had issues with the duration printing out with letters like e-09. 我在使用e-09这样的字母打印时遇到了问题。 Here's how I fixed it:
以下是我修复它的方法:
auto start = std::chrono::high_resolution_clock::now();
< run your function or code here >
auto finish = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> elapsed = finish - start;
std::cout << "Elapsed Time: " << elapsed.count() << " seconds" << std::endl;
And now I get desired results: 现在我得到了理想的结果:
Elapsed Time: 34.406 seconds
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.