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

相关推荐
tnnnnt32 分钟前
C++多线程学习笔记
c++·多线程
creative_mind1 小时前
My Greedy Algorithm(贪心算法)之路(一)
c++·算法·贪心算法
王红花x1 小时前
STL——list模拟实现
c++·学习·list
danaaaa3 小时前
算法力扣刷题记录 二十八【225. 用队列实现栈】
数据结构·c++·算法·leetcode·职场和发展
未来可期,静待花开~3 小时前
C++基础(八):类和对象 (下)
开发语言·jvm·c++
Caramel_biscuit3 小时前
C++专业面试真题(1)学习
c++·学习·面试
卫卫周大胖;3 小时前
【C++】多态(详解)
开发语言·c++
Java资深爱好者8 小时前
如何在std::map中查找元素
开发语言·c++
安步当歌11 小时前
【FFmpeg】av_write_trailer函数
c语言·c++·ffmpeg·视频编解码·video-codec
shuguang2580012 小时前
C++ 函数高级——函数重载——基本语法
开发语言·c++·visualstudio