概览
c++新标准提供了新的线程库,最近在写测试代码的时候需要让当前线程休眠,之前直接调用windows提供的Sleep()就好了,新标准中可以使用std::this_thread::sleep_for()或者std::this_thread::sleep_until()
来实现休眠。其中涉及到了std::chrono::duration和std::chrono::time_point。本篇只总结std::chrono::duration,std::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)。
注:
- 上文中的tick可以理解为周期,或时间单位。
- the number of seconds 表示是周期值基于秒来计算的。
类定义
std::chrono::duration是一个模板类,关键代码摘录如下(格式有调整):<