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

相关推荐
_OP_CHEN15 分钟前
【从零开始的Qt开发指南】(八)Qt 常用控件之显示类控件(上):Label 与 LCD Number 实战指南
开发语言·c++·qt·前端开发·图形化界面·qt常用控件·企业级组件
Yupureki17 分钟前
《算法竞赛从入门到国奖》算法基础:入门篇-模拟
c语言·数据结构·c++·算法·visual studio
仰泳的熊猫20 分钟前
1081 Rational Sum
数据结构·c++·算法·pat考试
程序猿编码25 分钟前
用 C++ 玩转字符级 Transformer 语言模型:从原理到实现
开发语言·c++·深度学习·语言模型·transformer
coderxiaohan27 分钟前
【C++】AVL树实现
开发语言·c++
liulilittle9 小时前
FileStream C++
开发语言·c++·cocoa
Gomiko9 小时前
C/C++基础(五):分支
c语言·c++
点PY9 小时前
C++ 中 std::async 和 std::future 的并发性
java·开发语言·c++
不会代码的小猴9 小时前
C++的第九天笔记
开发语言·c++·笔记
fqbqrr10 小时前
2512C++,clangd支持模块
开发语言·c++