//包含时钟和定时器标准库
#include<chrono>
#include<iostream>
using namespace std;
int main(){
//get the start time
auto time_point_start = chrono::steady_clock::now();
cout<<"start--------"<<endl;
int i = 0;
auto last_time = time_point_start;
//构造一个10ms的 duration实例,用于让此进程休眠
chrono::milliseconds ms10(10);
while(i<=100){
auto this_time = chrono::steady_clock::now();//注意记录时间差需要使用steady时钟,不可使用壁挂时钟
chrono::duration<double,milli>init_spend_time= this_time-time_point_start;//类有运算符重载 放心用
chrono::duration<double,milli>period_spend_time=this_time-last_time;
last_time = this_time;
//tick数需要使用.count()成员函数来得到
cout<<"run "<<i<<" times, now is"<<init_spend_time.count()<<"ms, period is "<<period_spend_time.count()<<"ms..."<<endl;
i++;
if(i>50) i=1;
//可能很多人用sleep_for 应该也没什么问题。我就是想让开始时间保持10ms一次。
this_thread::sleep_until(this_time+ms10);
}
if(chrono::steady_clock::is_steady) cout<<"steady clock is steady"<<endl;
auto end_time_high = chrono::steady_clock::now()-time_point_start;
cout<<"total time spend:"<<chrono::duration_cast<chrono::nanoseconds>(end_time_high).count()<<endl;
cout<<"exit..."<<endl;
return 0;
}
【C++标准库】------使用chrono记录代码时间间隔和执行周期
最新推荐文章于 2025-06-30 14:50:31 发布
本文演示了如何在C++中使用<chrono>库进行精确的时间测量和定时任务的实现。通过构造10毫秒的时延实例并利用steady_clock进行时间戳记录,实现了周期性的输出运行时间和周期时长。
182

被折叠的 条评论
为什么被折叠?



