[语法备忘]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
类型的方法。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧