[原]C++新标准之std::chrono::duration

本文介绍了C++新标准中的std::chrono::duration,用于表示时间间隔的类模板,包括其描述、类定义、duration_cast()转换功能以及预定义的duration类型,并通过示例展示了如何使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

概览

c++新标准提供了新的线程库,最近在写测试代码的时候需要让当前线程休眠,之前直接调用windows提供的Sleep()就好了,新标准中可以使用std::this_thread::sleep_for()或者std::this_thread::sleep_until()
来实现休眠。其中涉及到了std::chrono::durationstd::chrono::time_point。本篇只总结std::chrono::durationstd::chrono::time_point会再写一篇总结。

std::chrono::duration

描述

std::chrono::duration定义在 文件中,用来表示一个时间段。

cppreference上的原话如下:

Class template std::chrono::duration represents a time interval.
It consists of a count of ticks of type Rep and a tick period, where the tick period is a compile-time rational constant representing the number of seconds from one tick to the next.
The only data stored in a duration is a tick count of type Rep. If Rep is floating point, then the duration can represent fractions of ticks. Period is included as part of the duration's type, and is only used when converting between different durations.

Rep参数代表了可以传入的时间单位的类型,可以为float, int, int64等等,如果为float表示可以传入时间单位的一部分,比如传入1.2表示1.2倍个时间单位
Period参数代表了时间单位,可以为微秒,毫秒,秒,分钟,小时等(或者其它自定义的单位,类型为std::ratio)。

注:

  1. 上文中的tick可以理解为周期,或时间单位。
  2. the number of seconds 表示是周期值基于秒来计算的。

类定义

std::chrono::duration是一个模板类,关键代码摘录如下(格式有调整):<

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值