std::chrono::时钟

 

system_clock,起点是epoch,即1970-01-01 00:00:00 UTC,其刻度是1个tick,也就是_XTIME_NSECS_PER_TICK纳秒。

 

steady_clock的刻度是1纳秒,起点并非1970-01-01 00:00:00 UTC,一般是系统启动时间。

 

high_resolution_clocksystem_clocksteady_clock之一,根据情况使用。

 

// 当前时间
steady_clock::time_point tpNow = steady_clock::now(); // 小时 auto n = std::chrono::duration_cast<std::chrono::hours>(tpNow - GetLastSyncTimepoint()).count(); // 分钟 auto n = std::chrono::duration_cast<std::chrono::seconds>(tpNow - GetLastHeartbitTimepoint()).count();

 

// 跨平台时间戳工具类
#ifndef _CETimestamp_hpp_
#define _CETimestamp_hpp_ #include<chrono> using namespace std::chrono; class CETimestamp { public: CETimestamp() { update(); } ~CETimestamp() {} void update() { _begin = high_resolution_clock::now(); } /** * 获取当前秒 */ double getElapsedSecond() { return getElapsedTimeInMicroSec() * 0.000001; } /** * 获取毫秒 */ double getElapsedTimeInMilliSec() { return this->getElapsedTimeInMicroSec() * 0.001; } /** * 获取微妙 */ long long getElapsedTimeInMicroSec() { return duration_cast<microseconds>(high_resolution_clock::now() - _begin).count(); } protected: time_point<high_resolution_clock> _begin; }; #endif

 

 

// win下时间戳工具类
#ifndef _CELLWINTimestamp_hpp_
#define _CELLWINTimestamp_hpp_ #include <windows.h> class CEWINTimestamp { public: CEWINTimestamp() { QueryPerformanceFrequency(&_frequency); QueryPerformanceCounter(&_startCount); } ~CEWINTimestamp() {} void update() { QueryPerformanceCounter(&_startCount); } /** * 获取当前秒 */ double getElapsedSecond() { return getElapsedTimeInMicroSec() * 0.000001; } /** * 获取毫秒 */ double getElapsedTimeInMilliSec() { return this->getElapsedTimeInMicroSec() * 0.001; } /** * 获取微妙 */ long long getElapsedTimeInMicroSec() { LARGE_INTEGER endCount; QueryPerformanceCounter(&endCount); double startTimeInMicroSec = _startCount.QuadPart * (1000000.0 / _frequency.QuadPart); double endTimeInMicroSec = endCount.QuadPart * (1000000.0 / _frequency.QuadPart); return endTimeInMicroSec - startTimeInMicroSec; } protected: LARGE_INTEGER _frequency; LARGE_INTEGER _startCount; }; #endif

 

posted @ 2021-03-13 16:26  osbreak  阅读(238)  评论(0编辑  收藏  举报