[语法备忘]C++11特性:chrono库-时钟与计时器
Description
以前写密码算法实现的时候一直用的#include <ctime>。这次在品鉴微软的代码的时候获悉c++11有个新特性是专门的时间库,只能说以前C++ Primer没有看得很仔细。
Tips
来自c++ reference的说明。
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.
使用的时候需要加上std::chrono::xxx使用。
使用方式
简单粗暴的使用方式为直接使用如下模板套,中间注释的部分为需要计时的部分:
#include <iostream>
#include <chrono>
using namespace std;
int main ()
{
chrono::high_resolution_clock::time_point time_start, time_end;
time_start = chrono::high_resolution_clock::now();
//add your code here
time_end = chrono::high_resolution_clock::now();
chrono::milliseconds time_diff;
time_diff = chrono::duration_cast<chrono::milliseconds>(time_end - time_start);
cout << "time consuming: " << time_diff.count() << << endl;
return 0;
}
time_start和time_end是用来卡表的,这个精确度输出的单位为毫秒(ms),一般够用。
时间单位:duration类型
可以选用的时间单位(精确度)有:hours,minutes,seconds,milliseconds,microseconds,nanoseconds。在初始化time_diff变量的时候改变一下类型就行。
clock
有三种参考时钟类system_clock,steady_clock,high_resolution_clock。无脑选高精没什么问题,系统时钟可能会有改动的问题导致不够准确,因为时间还是由时间戳判断的。
time_point
time_point是一个时间点类型,由clock和duration决定,即由标准时钟和度过的时间决定,使用now()方法就可以得到一个时间点类型。
此外,最后使用(time_end-time_start).count()两个time_point类型相减得到的是一个duration类型,count()是一个duration类型的方法。

浙公网安备 33010602011771号