封装 C++11 chrono
程序大乐猿
共 1398字,需浏览 3分钟
·
2021-09-18 00:00
封装 TimerCounter
```c++
class TimerCounter
{
public:
TimerCounter(const std::string& flag, bool enable_cout = true, long threshlod = -1) :
_enable_cout(enable_cout), _threshlod(threshlod)
{
_start = get_current_us();
this->_flag = flag;
}
~TimerCounter() {
if(_enable_cout)
{
long delta = get_time_ms_elapsed();
if(delta > _threshold)
{
std::cout << _flag << " Timer elasped:" << delta << "ms" << std::endl;
}
}
}
int64_t get_current_us() {
auto now = std::chrono::system_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(now.time_since_epoch());
return duration.count();
}
long get_time_ms_elapsed() {
long end = get_current_us();
long n = (end - start) / 1000;
return n;
}
private:
bool _enable_cout;
std::string _flag;
long _threshold;
long _start;
};
```
测试
int main() {
std::cout << "###############" << std::endl;
// 出括号 TimerCounter 析构,
{
TimerCounter time;
std::this_thread::sleep_for(std::chrono::minutes(10));
}
std::cout << "********" << std::endl;
return 0;
}
评论