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();
}
}
标签:chrono,打印,timer,bool,c++,time,msg,Type
From: https://www.cnblogs.com/AngleLin/p/17043856.html