C++11时间日期库chrono的使用
chrono是c++11中新加入的时间日期操作库,可以方便地进行时间日期操作,主要包含了:duration, time_point, clock。
时钟与时间点
chrono中用time_point模板类表示时间点,其支持基本算术操作;不同时钟clock分别返回其对应类型的时间点。
clock
时钟是从一个时点开始,按照某个刻度的计数;chrono同时提供了三种时钟(通过now()获取当前时间点):
- system_clock:系统时钟,相对epoch(1970-01-01 00:00:00utc)的时间间隔;
- steady_clock:单调时钟,只能增长(后一次调用now()得到的时间总是比前一次的值大);一般是相对于系统启动时间的时间间隔;
- high_resolution_clock:高精度时钟(当前系统能提供的最高精度时钟,很可能就是steady_clock),也是单调的;
需要得到绝对时点的场景使用system_clock;需要得到时间间隔,且不受系统时间修改而受影响时使用steady_clock。
时间显示
在c++20中直接有to_stream直接输出system_clock时钟;但在此之前,只能通过间接的方式来输出:
auto tnow = system_clock::now(); auto tmnow = system_clock::to_time_t(tnow); auto locnow = std::localtime(&tmnow); cout<<std::put_time(locnow, "%y-%m-%d %h:%m:%s")<<endl; // 2019-12-20 19:35:12
system_clock::from_time_t(...)可以把time_t类型时间转换为time_point,便于chrono使用。
运行计时
通过steady_clock/high_resolution_clock可方便的进行计时:
public: explicit xruntime{bool bstart){ if(bstart) restart(); } void restart(){ m_tpstart = high_resolution_clock::now(); } double stop(){ return operator()(); } double operator()(void){ auto tpend = high_resolution_clock::now(); auto elap = tpend - m_tpstart; return (double)elap.count() / std::nano::den; //返回运行的秒数,如1.00345 } }
时间间隔duration
chrono中使用duration模板类来表示时间间隔,并定义了从小时到纳秒的时间间隔。
duration模板
duration使用一个数值(表示时钟数)和分数(ratio)来表示具体间隔。支持基本的算术运算,并通过count()获取具体的时钟数。
template<typename _rep, typename _period = ratio<1>> struct duration { typedef _rep rep; constexpr _rep count() const{ return (_myrep); } ... private: _rep _myrep; //时钟计数 };
基准是秒,并依次定义了常用的间隔,如:
typedef duration<long long> seconds; typedef duration<long long, milli> milliseconds; typedef duration<long long, ratio<3600>> hours;
不同的时间间隔可以直接进行算术运算,如休眠需要毫秒参数,我们可以封装接收秒与毫秒的接口:
void mysleep(int nsec, int nmillsec){ std::chrono::seconds secs(nsec); std::chrono::milliseconds mills(nmillsec); std::this_thread::sleep_for(secs+mills); }
duration_cast
使用duration_cast可以方便的在不同时间单位间进行转换,如:
auto sec=seconds(123); auto minu=duration_cast<minutes>(sec); cout<<sec.count()<<","<<minu.count()<<endl; // 123,2
ratio
ratio是一个分数模板类,第一个参数为分子,第二个参数为分母;通过静态成员可获取:
- num:分子
- den:分母
typedef ratio<1, 1000> milli; typedef ratio<1000, 1> kilo; cout<<milli::den<<endl; // 1000
到此这篇关于c++11时间日期库chrono的使用的文章就介绍到这了,更多相关c++11时间日期库chrono 内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
上一篇: vue3.0新语法的基本使用
推荐阅读
-
php 时间time与日期date之间的使用详解及区别
-
Android中TimePicker与DatePicker时间日期选择组件的使用实例
-
使用elementUI的日期时间选择器+下拉菜单+tab切换+table表格完成排行榜的切换及按年月周查询(部分代码)
-
MySQL求两个时间的时间差 博客分类: MySQL数据库 MySQL求时间差日期
-
oracle trunc函数的使用 博客分类: 【数据库】 trunctrunc日期trunc数字
-
Java8时间日期库中的常用使用示例
-
Java8时间日期库中的常用使用示例
-
asp.net下日期和时间处理的类库
-
asp.net下日期和时间处理的类库
-
Java 8新的时间日期库的20个使用示例