在C++11中,<chrono>是标准模板库中与时间有关的头文件。该头文件中所有函数与类模板均定义在std::chrono命名空间中。

std::chrono是在C++11中引入的,是一个模板库,用来处理时间和日期的Time library。要使用chrono库,需要include<chrono>,其所有实现均在chrono命名空间下。

std::chrono::duration:记录时间长度的,表示一段时间,如1分钟、2小时、10毫秒等。表示为类模板duration的对象,用一个count representation与一个period precision表示。例如,10毫秒的10为count representation,毫秒为period precision。

template<class Rep, class Period = ratio<1> > class duration;

第一个模板参数为表示时间计数的数据类型。成员函数count返回该计数。第二个模板参数表示计数的一个周期,一般是std::ratio类型,表示一个周期(即一个时间嘀嗒tick)是秒钟的倍数或分数,在编译时应为一个有理数常量。

std::chrono::time_point:记录时间点的,表示一个具体时间。例如某人的生日、今天的日出时间等。表示为类模板time_point的对象。用相对于一个固定时间点epoch的duration来表示。

std::chrono::clocks:时间点相对于真实物理时间的框架。至少提供了3个clock:

(1)、system_clock:当前系统范围(即对各进程都一致)的一个实时的日历时钟(wallclock)。

(2)、steady_clock:当前系统实现的一个维定时钟,该时钟的每个时间嘀嗒单位是均匀的(即长度相等)。

(3)、high_resolution_clock:当前系统实现的一个高分辨率时钟。

chrono is the name of a header, but also of a sub-namespace: All the elements in this header(except for the common_type specializations) are not defined directly under the std namespace (like most of the standard library) but under the std::chrono namespace.

The elements in this header deal with time. This is done mainly by means of three concepts:

(1)、Durations: They measure time spans, like: one minute, two hours, or ten milliseconds. In this library, they are represented with objects of the duration class template, that couples a count representation and a period precision (e.g., ten milliseconds has ten as count representation and milliseconds as period precision).

(2)、Time points:A reference to a specific point in time, like one's birthday, today's dawn, or when the next train passes. In this library, objects of the time_point class template express this by using a duration relative to an epoch (which is a fixed point in time common to all time_point objects using the same clock).

(3)、Clocks: A framework that relates a time point to real physical time. The library provides at least three clocks that provide means to express the current time as a time_point: system_clock, steady_clock and high_resolution_clock.

std::chrono::duration:A duration object expresses a time span by means of a count and a period.

std::chrono::duration_values:This is a traits class to provide the limits and zero value of the type used to represent the count in a duration object.

std::chrono::high_resolution_clock:The members of clock classes provide access to the current time_point.high_resolution_clock is the clock with the shortest tick period. It may be a synonym for system_clock or steady_clock.

std::chrono::steady_clock/std::chrono::system_clock:Clock classes provide access to the current time_point. system_clock is a system-wide realtime clock. steady_clock is specifically designed to calculate time intervals.

std::chrono::time_point:A time_point object expresses a point in time relative to a clock's epoch.

下面是从其他文章中copy的<chrono>测试代码,详细内容介绍可以参考对应的reference:

#include "chrono.hpp"
#include <chrono>
#include <iostream>
#include <ratio>
#include <ctime>
#include <iomanip>///
// reference: http://www.cplusplus.com/reference/chrono/duration/
int test_chrono_duration()
{
{ // duration::duration: Constructs a duration object// chrono::duration_cast: Converts the value of dtn into some other duration type,// taking into account differences in their periodstypedef std::chrono::duration<int> seconds_type;typedef std::chrono::duration<int, std::milli> milliseconds_type;typedef std::chrono::duration<int, std::ratio<60 * 60>> hours_type;hours_type h_oneday(24);                  // 24hseconds_type s_oneday(60 * 60 * 24);          // 86400smilliseconds_type ms_oneday(s_oneday);    // 86400000msseconds_type s_onehour(60 * 60);            // 3600s//hours_type h_onehour (s_onehour);          // NOT VALID (type truncates), use:hours_type h_onehour(std::chrono::duration_cast<hours_type>(s_onehour));milliseconds_type ms_onehour(s_onehour);  // 3600000ms (ok, no type truncation)std::cout << ms_onehour.count() << "ms in 1h" << std::endl;
}{ // duration operators: +、-、*、/、>、<、!=、and so onstd::chrono::duration<int> foo;std::chrono::duration<int> bar(10);// counts: foo bar//         --- ---foo = bar;                 // 10  10foo = foo + bar;           // 20  10++foo;                     // 21  10--bar;                     // 21   9foo *= 2;                  // 42   9foo /= 3;                  // 14   9//bar +=  (foo % bar);      // 14  14std::cout << std::boolalpha;std::cout << "foo==bar: " << (foo == bar) << std::endl;std::cout << "foo: " << foo.count() << std::endl;std::cout << "bar: " << bar.count() << std::endl;
}{ // duration::count: Returns the internal count (i.e., the representation value) of the duration object.using namespace std::chrono;// std::chrono::milliseconds is an instatiation of std::chrono::duration:milliseconds foo(1000); // 1 secondfoo *= 60;std::cout << "duration (in periods): ";std::cout << foo.count() << " milliseconds.\n";std::cout << "duration (in seconds): ";std::cout << foo.count() * milliseconds::period::num / milliseconds::period::den;std::cout << " seconds.\n";
}{ // duration::max: Returns the maximum value of duration// duration::min: Returns the minimum value of durationstd::cout << "system_clock durations can represent:\n";std::cout << "min: " << std::chrono::system_clock::duration::min().count() << "\n";std::cout << "max: " << std::chrono::system_clock::duration::max().count() << "\n";
}{ // duration::zero: Returns a duration value of zerousing std::chrono::steady_clock;steady_clock::time_point t1 = steady_clock::now();std::cout << "Printing out something...\n";steady_clock::time_point t2 = steady_clock::now();steady_clock::duration d = t2 - t1;if (d == steady_clock::duration::zero())std::cout << "The internal clock did not tick.\n";elsestd::cout << "The internal clock advanced " << d.count() << " periods.\n";
}{ // chrono::time_point_cast: Converts the value of tp into a time_point type with a different duration internal object,// taking into account differences in their durations's periods.using namespace std::chrono;typedef duration<int, std::ratio<60 * 60 * 24>> days_type;time_point<system_clock, days_type> today = time_point_cast<days_type>(system_clock::now());std::cout << today.time_since_epoch().count() << " days since epoch" << std::endl;
}return 0;
}//
// reference: http://www.cplusplus.com/reference/chrono/high_resolution_clock/
int test_chrono_high_resolution_clock()
{// high_resolution_clock::now: Returns the current time_point in the frame of the high_resolution_clockusing namespace std::chrono;high_resolution_clock::time_point t1 = high_resolution_clock::now();std::cout << "printing out 1000 stars...\n";for (int i = 0; i<1000; ++i) std::cout << "*";std::cout << std::endl;high_resolution_clock::time_point t2 = high_resolution_clock::now();duration<double> time_span = duration_cast<duration<double>>(t2 - t1);std::cout << "It took me " << time_span.count() << " seconds.";std::cout << std::endl;return 0;
}///
// reference: http://www.cplusplus.com/reference/chrono/steady_clock/
int test_chrono_steady_clock()
{// steady_clock is specifically designed to calculate time intervals.// steady_clock::now: Returns the current time_point in the frame of the steady_clock.using namespace std::chrono;steady_clock::time_point t1 = steady_clock::now();std::cout << "printing out 1000 stars...\n";for (int i = 0; i<1000; ++i) std::cout << "*";std::cout << std::endl;steady_clock::time_point t2 = steady_clock::now();duration<double> time_span = duration_cast<duration<double>>(t2 - t1);std::cout << "It took me " << time_span.count() << " seconds.";std::cout << std::endl;return 0;
}//
// reference: http://www.cplusplus.com/reference/chrono/system_clock/
int test_chrono_system_clock()
{// system_clock is a system-wide realtime clock.{ // system_clock::from_time_t: Converts t into its equivalent of member type time_point.using namespace std::chrono;// create tm with 1/1/2000:std::tm timeinfo = std::tm();timeinfo.tm_year = 100;   // year: 2000timeinfo.tm_mon = 0;      // month: januarytimeinfo.tm_mday = 1;     // day: 1ststd::time_t tt = std::mktime(&timeinfo);system_clock::time_point tp = system_clock::from_time_t(tt);system_clock::duration d = system_clock::now() - tp;// convert to number of days:typedef duration<int, std::ratio<60 * 60 * 24>> days_type;days_type ndays = duration_cast<days_type> (d);// display result:std::cout << ndays.count() << " days have passed since 1/1/2000";std::cout << std::endl;
}{ // system_clock::now: Returns the current time_point in the frame of the system_clockusing namespace std::chrono;duration<int, std::ratio<60 * 60 * 24> > one_day(1);system_clock::time_point today = system_clock::now();system_clock::time_point tomorrow = today + one_day;time_t tt;tt = system_clock::to_time_t(today);std::cout << "today is: " << ctime(&tt);tt = system_clock::to_time_t(tomorrow);std::cout << "tomorrow will be: " << ctime(&tt);
}{ // system_clock::to_time_t: Converts tp into its equivalent of type time_t.using namespace std::chrono;duration<int, std::ratio<60 * 60 * 24> > one_day(1);system_clock::time_point today = system_clock::now();system_clock::time_point tomorrow = today + one_day;time_t tt;tt = system_clock::to_time_t(today);std::cout << "today is: " << ctime(&tt);tt = system_clock::to_time_t(tomorrow);std::cout << "tomorrow will be: " << ctime(&tt);
}return 0;
}//
// reference: http://www.cplusplus.com/reference/chrono/time_point/
int test_chrono_time_point()
{
{ // time_point operators: +、-、==、!=using namespace std::chrono;system_clock::time_point tp, tp2;                // epoch valuesystem_clock::duration dtn(duration<int>(1));  // 1 second//  tp     tp2    dtn//  ---    ---    ---tp += dtn;          //  e+1s   e      1stp2 -= dtn;         //  e+1s   e-1s   1stp2 = tp + dtn;     //  e+1s   e+2s   1stp = dtn + tp2;     //  e+3s   e+2s   1stp2 = tp2 - dtn;    //  e+3s   e+1s   1sdtn = tp - tp2;     //  e+3s   e+1s   2sstd::cout << std::boolalpha;std::cout << "tp == tp2: " << (tp == tp2) << std::endl;std::cout << "tp > tp2: " << (tp>tp2) << std::endl;std::cout << "dtn: " << dtn.count() << std::endl;
}{ // time_point::time_point: Constructs a time_point objectusing namespace std::chrono;system_clock::time_point tp_epoch;  // epoch valuetime_point <system_clock, duration<int>> tp_seconds(duration<int>(1));system_clock::time_point tp(tp_seconds);std::cout << "1 second since system_clock epoch = ";std::cout << tp.time_since_epoch().count();std::cout << " system_clock periods." << std::endl;// display time_point:std::time_t tt = system_clock::to_time_t(tp);std::cout << "time_point tp is: " << ctime(&tt);
}{ // time_point::time_since_epoch: Returns a duration object with the time span value between the epoch and the time pointusing namespace std::chrono;system_clock::time_point tp = system_clock::now();system_clock::duration dtn = tp.time_since_epoch();std::cout << "current time since epoch, expressed in:" << std::endl;std::cout << "periods: " << dtn.count() << std::endl;std::cout << "seconds: " << dtn.count() * system_clock::period::num / system_clock::period::den;std::cout << std::endl;
}return 0;
}///
// reference: https://zh.wikibooks.org/wiki/C%2B%2B/STL/Chrono
static long fibonacci(unsigned n)
{if (n < 2) return n;return fibonacci(n - 1) + fibonacci(n - 2);
}int test_chrono_1()
{
{ // std::chrono::time_pointstd::chrono::system_clock::time_point now = std::chrono::system_clock::now();std::time_t now_c = std::chrono::system_clock::to_time_t(now - std::chrono::hours(24));std::cout << "24 hours ago, the time was " << now_c << '\n';std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();std::cout << "Hello World\n";std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();std::cout << "Printing took "<< std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() << "us.\n";
}{ // std::chrono::durationusing shakes = std::chrono::duration<int, std::ratio<1, 100000000>>;using jiffies = std::chrono::duration<int, std::centi>;using microfortnights = std::chrono::duration<float, std::ratio<12096, 10000>>;using nanocenturies = std::chrono::duration<float, std::ratio<3155, 1000>>;std::chrono::seconds sec(1);std::cout << "1 second is:\n";std::cout << std::chrono::duration_cast<shakes>(sec).count() << " shakes\n";std::cout << std::chrono::duration_cast<jiffies>(sec).count() << " jiffies\n";std::cout << microfortnights(sec).count() << " microfortnights\n";std::cout << nanocenturies(sec).count() << " nanocenturies\n";
}{ // std::chrono::time_point<std::chrono::system_clock> start, end;start = std::chrono::system_clock::now();std::cout << "f(42) = " << fibonacci(42) << '\n';end = std::chrono::system_clock::now();std::chrono::duration<double> elapsed_seconds = end - start;std::time_t end_time = std::chrono::system_clock::to_time_t(end);std::cout << "finished computation at " << std::ctime(&end_time)<< "elapsed time: " << elapsed_seconds.count() << "s\n";
}return 0;
}

GitHub:https://github.com/fengbingchun/Messy_Test

C++11中头文件chrono的使用相关推荐

  1. C++11中头文件thread的使用

    C++11中加入了<thread>头文件,此头文件主要声明了std::thread线程类.C++11的标准类std::thread对线程进行了封装.std::thread代表了一个线程对象 ...

  2. C++11中头文件type_traits介绍

    C++11中的头文件type_traits定义了一系列模板类,在编译期获得某一参数.某一变量.某一个类等等类型信息,主要做静态检查. 此头文件包含三部分: (1).Helper类:帮助创建编译时常量的 ...

  3. C++11中头文件atomic的使用

    原子库为细粒度的原子操作提供组件,允许无锁并发编程.涉及同一对象的每个原子操作,相对于任何其他原子操作是不可分的.原子对象不具有数据竞争(data race).原子类型对象的主要特点就是从不同线程访问 ...

  4. C++/C++11中头文件sstream介绍

    C++使用标准库类来处理面向流的输入和输出:(1).iostream处理控制台IO:(2).fstream处理命名文件IO:(3).stringstream完成内存string的IO. 类fstrea ...

  5. C++/C++11中头文件functional的使用

    <functional>是C++标准库中的一个头文件,定义了C++标准中多个用于表示函数对象(function object)的类模板,包括算法操作.比较操作.逻辑操作:以及用于绑定函数对 ...

  6. C++11中头文件ratio的使用

    include<ratio>是在C++11中引入的,在此文件中有一些模板类. 模板类std::ratio及相关的模板类(如std::ratio_add)提供编译时有理数算术支持.此模板的每 ...

  7. C++/C++11中头文件algorithm的使用

    <algorithm>是C++标准程序库中的一个头文件,定义了C++ STL标准中的基础性的算法(均为函数模板).<algorithm>定义了设计用于元素范围的函数集合.任何对 ...

  8. C++/C++11中头文件numeric的使用

    <numeric>是C++标准程序库中的一个头文件,定义了C++ STL标准中的基础性的数值算法(均为函数模板): (1).accumulate: 以init为初值,对迭代器给出的值序列做 ...

  9. C++/C++11中头文件iterator的使用

    <iterator>是C++标准程序库中的一个头文件,定义了C++ STL标准中的一些迭代器模板类,这些类都是以std::iterator为基类派生出来的.迭代器提供对集合(容器)元素的操 ...

最新文章

  1. 在python中print 应用_Python print正确使用方法浅析
  2. awk 求三角形重心
  3. 【译】UNIVERSAL IMAGE LOADER. PART 3---ImageLoader详解
  4. 简单struts,spring,mybatis组合使用
  5. 使用form上传文件到application server的另一种办法
  6. matlab求距离判别函数,求MATLAB的逐步判别程序 - 仿真模拟 - 小木虫 - 学术 科研 互动社区...
  7. Bootstrap-CSS:表格
  8. 使用组策略推送exchange自签名证书
  9. 安卓能硬改的手机机型_【每日新闻】小米11部分镜头参数爆料;华为重新采购手机零部件 重启4G手机生产...
  10. 动手学深度学习(PyTorch实现)(九)--VGGNet模型
  11. 数据缓存 php,数据缓存 · ThinkPHP3.2.3完全开发手册 · 看云
  12. 计算机主机内有哪些部件常用的,智慧职教: 计算机系统由什么组成?计算机主机内有哪些部件?常用的计算机外设有哪些...
  13. 《C++ 进阶心法》书籍修正记录
  14. AngularJS 快速入门
  15. web前端 html+css+javascript网页设计实例 家乡网站制作
  16. 计算机课英语怎么读音标,【英语课堂】48个国际音标表及发音详解图
  17. 架构整洁之道 (Clean Architecture )与领域模型与领域驱动设计(DDD)
  18. Centos调整分区存储大小
  19. python 模拟百度搜索关键词
  20. KingbaseES Clusterware 高可用案例之---构建iSCSI共享存储

热门文章

  1. 在Ubuntu18.04下的Cmake使用记录
  2. Gradient Descent梯度下降(透彻分析)
  3. 设备连接:Ubuntu16.04 ROS中连接Hokuyo激光雷达UTM-30LX-EW
  4. 基于语义分割的视频弹幕防挡实现(训练、测试、部署实现)
  5. ADPRL - 近似动态规划和强化学习 - Note 6 - Mitigating the Curse of Dimensionality
  6. Unity导出apk出现的问题,JDK,Android SDK,NDK,无“安装模块”
  7. ue5新手零基础学习教程 Unreal Engine 5 Beginner Tutorial - UE5 Starter Course
  8. iOS开发网络篇—HTTP协议
  9. 8. 进制转化的函数
  10. include_once 问题