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

相关推荐
郝学胜-神的一滴1 分钟前
解锁CS数据存储的核心逻辑:从结构选择到表单设计的全解析
linux·服务器·数据库·c++·后端·oracle
Q741_14719 分钟前
每日一题 力扣 3418. 机器人可以获得的最大金币数 力扣 215. 数组中的第K个最大元素 动态规划 TopK问题 C++ 题解
c++·算法·leetcode·动态规划·topk
haibindev19 分钟前
写了10年代码的人,在AI编程时代反而最值钱
c++·ai编程·claude
寻寻觅觅☆28 分钟前
东华OJ-基础题-31-素数(C++)
开发语言·c++·算法
Mr_Xuhhh38 分钟前
C++算法刷题:排序子序列、削减整数、最长上升子序列(二)题解
开发语言·c++·算法
tankeven40 分钟前
HJ157 剪纸游戏
c++·算法
顶点多余1 小时前
死锁+线程安全
linux·开发语言·c++·系统安全
艾莉丝努力练剑1 小时前
【Linux线程】Linux系统多线程(二):线程的优缺点
linux·运维·服务器·c++·学习
yunn_1 小时前
Qt 多线程
c++·qt
Yu_Lijing1 小时前
基于C++的《Head First设计模式》笔记——MVC模式
c++·笔记·设计模式