C++11 chrono high_resolution_clock实现计时器

程序参考《深入应用C++11 代码优化与工程级应用》,使用high_resolution_clock实现计时器,在测试程序性能时会用到,测试程序的耗时。

high_resolution_clock:
高精度时钟,时钟类的成员,提供对当前time_point的访问。

high_resolution_clock 是间隔周期最短的时钟。它可能是system_clock或steady_clock的别名。

time_point表示一个时间点,用来获取从它的clock的纪元开始所经过的时间(比如1970.1.1以来的时间间隔)和当前的时间。

#ifndef TIME_HPP
#define TIME_HPP

#include <chrono>
using namespace std;
using namespace std::chrono;

class MyTimer{
public:
    MyTimer(){
       m_begin = high_resolution_clock::now();
       m_end = m_begin;
    }
    void reset()
    {
        m_begin = high_resolution_clock::now();
        m_end = m_begin;
    }

    void end()
    {
        this->m_end = high_resolution_clock::now();
    }

    //默认输出毫秒
    template<typename Duration=milliseconds>
    int64_t elapsed() const
    {

        return duration_cast<Duration>(this->m_end - m_begin).count();
    }

    //微妙
    int64_t elapsed_micro() const{
        return elapsed<microseconds>();
    }

    //nano second
    int64_t elapsed_nano() const{
        return elapsed<nanoseconds>();
    }

    //second
    int64_t elapsed_seconds() const{
        return elapsed<seconds>();
    }

    //minute
    int64_t elapsed_minutes() const
    {
        return elapsed<minutes>();
    }

    //hour
    int64_t elapsed_hour() const
    {
        return elapsed<hours>();
    }

private:
    time_point<high_resolution_clock> m_begin;
    time_point<high_resolution_clock> m_end;
};


#endif // TIME_HPP

#include <time.h>
#include <Windows.h>
#include <stdio.h>

#include "time.hpp"
#include <iostream>
#include <thread>
using namespace std;

int func()
{
    int a=0;
    for (int i=0; i<100000; i++)
    {
        std::this_thread::sleep_for(chrono::nanoseconds(2));
        a += i;
    }
    return a;
}

int main()
{
    MyTimer t;
    func();
    t.end();

    cout<<t.elapsed()<<endl;
    cout<<t.elapsed_micro()<<endl;
    cout<<t.elapsed_nano()<<endl;
    cout<<t.elapsed_seconds()<<endl;
    cout<<t.elapsed_minutes()<<endl;
    cout<<t.elapsed_hour()<<endl;

    return 0;
}

结果:

5
5004
5004400
0
0
0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值