C++精确计时

本文首先通过QueryPerformanceFrequency获取高精度计时器的时钟频率,然后通过两次调用QueryPerformanceCounter获取高精度计时器的差值,最后以差值除以时钟频率获取精确计时。

但要注意,时钟频率及计时器的值均为LONGLONG类型,需转换为double后才能计算精确的秒数。

以下为代码:

LARGE_INTEGER frequency;
LARGE_INTEGER start;
LARGE_INTEGER stop;

QueryPerformanceFrequency(&frequency); //获取计时器的时钟频率
QueryPerformanceCounter(&start); //获得计数器初始值
Sleep(10); //耗时操作(暂停10ms)
QueryPerformanceCounter(&stop); //获得计数器终止值

const auto interval = static_cast<double>(stop.QuadPart - start.QuadPart);
const auto timeSpanSecond = interval / frequency.QuadPart; //获取秒数
const auto timeSpanMillisecond = timeSpanSecond * 1000.0; //获取毫秒数
std::cout << "Sleep(10) takes " << timeSpanMillisecond << "ms." << std::endl;

下面为结果:

 

posted @ 2020-04-24 16:52  xhubobo  阅读(1280)  评论(0编辑  收藏  举报