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

相关推荐
胡萝卜3.018 分钟前
掌握string类:从基础到实战
c++·学习·string·string的使用
江公望30 分钟前
通过QQmlExtensionPlugin进行Qt QML插件开发
c++·qt·qml
Syntech_Wuz34 分钟前
从 C 到 C++:容器适配器 std::stack 与 std::queue 详解
数据结构·c++·容器··队列
艾莉丝努力练剑2 小时前
【C++STL :stack && queue (一) 】STL:stack与queue全解析|深入使用(附高频算法题详解)
linux·开发语言·数据结构·c++·算法
胡萝卜3.02 小时前
深入理解string底层:手写高效字符串类
开发语言·c++·学习·学习笔记·string类·string模拟实现
kyle~2 小时前
计算机系统---CPU的进程与线程处理
linux·服务器·c语言·c++·操作系统·计算机系统
只是懒得想了2 小时前
用C++实现一个高效可扩展的行为树(Behavior Tree)框架
java·开发语言·c++·design-patterns
bkspiderx2 小时前
C++设计模式之行为型模式:模板方法模式(Template Method)
c++·设计模式·模板方法模式
我是华为OD~HR~栗栗呀2 小时前
华为OD-23届考研-Java面经
java·c++·后端·python·华为od·华为·面试
mit6.8243 小时前
pq|二维前缀和
c++