c++ 利用 chrono 打印时间

c++ 利用 chrono 打印时间

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

头文件

#ifndef TIMER_H
#define TIMER_H
#include <chrono>

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

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

    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 // TIMER_H

源文件

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


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

}

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

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

void timer::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 timer::getTime(bool cont)
{
    pause();
    if (!cont) {
        start();
    }
}

原文链接: https://www.cnblogs.com/AngleLin/p/17043856.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    c++ 利用 chrono 打印时间

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/311172

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月16日 上午11:54
下一篇 2023年2月16日 上午11:54

相关推荐