c++ 利用 chrono 打印时间

自己封装的一个打印时间的类,可以打印秒、毫秒、微秒、纳秒。

使用方式

#include "
int main() {
    myTimer timer("message");

    // do something;

    return 0;
}

从创建的地方开始计时,析构时自动打印:从创建到析构所经历的时间。
中间还可以用 getTime() 打印:从创建到执行到这行代码所经历的时间。

头文件

#ifndef MYTIMER_H
#define MYTIMER_H
#include <chrono>

enum class Type {
    MS, //millisecond
    US, //microsecond
    NS, //nanosecond
    S   //second
};

class myTimer
{
    typedef std::chrono::steady_clock::time_point timePoint;
public:
    myTimer(const char *msg, Type type = Type::S, bool dumpOnDestruct = true, bool startOnConstruct = true);
    ~myTimer();

    void            getTime(bool cont = false);

protected:
    void            start();
    void            pause();

protected:
    const char*     _msg;
    bool            _dumpOnDestruct;
    bool            _active;
    Type            _type;
    timePoint       _startTime;
    timePoint       _endTime;
};

#endif // MYTIMER_H

源文件

#include "myTimer.h"
#include <string>


myTimer::myTimer(const char *msg, Type type, bool dumpOnDestruct, bool startOnConstruct)
    : _msg(msg), _dumpOnDestruct(dumpOnDestruct), _active(startOnConstruct), _type(type)
{
    if (_active)
        start();

}

myTimer::~myTimer()
{
    if (_dumpOnDestruct)
        pause();
}

void myTimer::start()
{
    _startTime = std::chrono::steady_clock::now();
}

void myTimer::pause()
{
    _endTime = std::chrono::steady_clock::now();
    double time;
    switch (_type) {
    case Type::MS:
        time = std::chrono::duration<double,std::milli>(_endTime - _startTime).count();
        printf("%s %6f ms\n", _msg, time);
        break;
    case Type::US:
        time = std::chrono::duration<double,std::micro>(_endTime - _startTime).count();
        printf("%s %6f us\n", _msg, time);
        break;
    case Type::NS:
        time = std::chrono::duration<double,std::nano>(_endTime - _startTime).count();
        printf("%s %6f ns\n", _msg, time);
        break;
    default:
        time = std::chrono::duration<double>(_endTime - _startTime).count();
        printf("%s %6f s\n", _msg, time);
        break;
    }
}

void myTimer::getTime(bool cont)
{
    pause();
    if (!cont) {
        start();
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值