Chrono

编程入门 行业动态 更新时间:2024-10-26 01:28:59
本文介绍了Chrono - 以毫秒为单位的两个时间点之间的差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

如何获得(使用 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 - 以毫秒为单位的两个时间点之间的差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 12:51:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1395149.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Chrono

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!