C++ Chrono - 以毫秒为单位的两个时间点之间的差异?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31657511/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 14:00:42  来源:igfitidea点击:

Chrono - The difference between two points in time in milliseconds?

c++c++11timechrono

提问by waas1919

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?

我怎样才能以毫秒为单位获得这个时间,所以我可以将持续时间用作无符号整数,而不是浮点数,然后乘以 1000?

回答by lisyarus

std::chrono::durationhas two template parameters, the second being exactly the unit of measure. You can invoke std::chrono::duration_castto cast from one duration type to another. Also, there is a predefined duration type for milliseconds: std::chrono::milliseconds. Composing this together:

std::chrono::duration有两个模板参数,第二个正是度量单位。您可以调用std::chrono::duration_cast从一种持续时间类型转换为另一种持续时间类型。此外,还有一个预定义的毫秒持续时间类型:std::chrono::milliseconds. 一起组成这个:

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::millisecondsis a signed integer of unspecified size.

它的返回类型是duration::rep,对于标准持续时间类型,它std::chrono::milliseconds是一个未指定大小的有符号整数。

回答by zoska

chrono::duration_cast<chrono::milliseconds>(end_time - start_time).count()

回答by johnjohnlys

回答by AceFunk

I had issues with the duration printing out with letters like e-09. Here's how I fixed it:

我在打印 e-09 之类的字母时遇到了持续时间问题。这是我修复它的方法:

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