【C++标准库】------使用chrono记录代码时间间隔和执行周期

本文演示了如何在C++中使用<chrono>库进行精确的时间测量和定时任务的实现。通过构造10毫秒的时延实例并利用steady_clock进行时间戳记录,实现了周期性的输出运行时间和周期时长。
//包含时钟和定时器标准库
#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;
    }
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小羊苏C

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值