自己封装的一个打印时间的类,可以打印秒、毫秒、微秒、纳秒。
| #include "myTimer.h" |
| int main() { |
| myTimer timer("message"); |
| |
| |
| |
| return 0; |
| } |
从创建的地方开始计时,析构时自动打印:从创建到析构所经历的时间。
中间还可以用 getTime()
打印:从创建到执行到这行代码所经历的时间。
| #ifndef MYTIMER_H |
| #define MYTIMER_H |
| #include <chrono> |
| |
| enum class Type { |
| MS, |
| US, |
| NS, |
| S |
| }; |
| |
| 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 |
| #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(); |
| } |
| } |