#pragma once class StopWatch { private: int _freq; LARGE_INTEGER _begin; LARGE_INTEGER _end; public: float costTime; //用时,*1000000 = 微秒, 1秒=1000000 StopWatch(void) { LARGE_INTEGER tmp; QueryPerformanceFrequency(&tmp); _freq = tmp.QuadPart; costTime = 0; } ~StopWatch(void) { } void Start() // 开始计时 { QueryPerformanceCounter(&_begin); } void End() // 结束计时 { QueryPerformanceCounter(&_end); costTime = ((_end.QuadPart - _begin.QuadPart)*1.0f / _freq); } void Reset() // 计时清0 { costTime = 0; } };
———————————————————————————————————————————————
#include “stdafx.h”
#include <iostream>
#include <crtdbg.h>
#include <sys/timeb.h>
#include <time.h>
#include <windows.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
LARGE_INTEGER startCount;
LARGE_INTEGER endCount;
LARGE_INTEGER freq;
QueryPerformanceFrequency(&freq);
QueryPerformanceCounter(&startCount);
//////////////////////////////////////////////////////////////////////////
///精确测试时间
//////////////////////////////////////////////////////////////////////////
Sleep(3500);
QueryPerformanceCounter(&endCount);
double elapsed = (double)(endCount.QuadPart – startCount.QuadPart) / freq.QuadPart;
cout << “Total time elapsed : ” << elapsed << endl;
system(“pause”);
return 0;
}
—————————————————————————————
QueryPerformanceFrequency() – 基本介绍
类型:Win32API
原型:BOOL QueryPerformanceFrequency(LARGE_INTEGER *lpFrequency);
作用:返回硬件支持的高精度计数器的频率。
返回值:非零,硬件支持高精度计数器;零,硬件不支持,读取失败。
QueryPerformanceFrequency() – 技术特点
供WIN9X使用的高精度定时器:QueryPerformanceFrequency()和QueryPerformanceCounter(),要求计算机从硬件上支持高精度定时器。
函数的原形是:
BOOL QueryPerformanceFrequency(LARGE_INTEGER *lpFrequency);
BOOL QueryPerformanceCounter (LARGE_INTEGER *lpCount);
数据类型LARGEINTEGER既可以是一个作为8字节长的整数,也可以是作为两个4字节长的整数的联合结构,其具体用法根据编译器是否支持64位而定。该类型的定义如下:
typeef union _ LARGE_INTEGER
{
struct
{
DWORD LowPart;
LONG HighPart;
};
LONGLONG QuadPart;
} LARGE_INTEGER;
在定时前应该先调用QueryPerformanceFrequency()函数获得机器内部计时器的时钟频率。接着在需要严格计时的事件发生前和发生之后分别调用QueryPerformanceCounter(),利用两次获得的计数之差和时钟频率,就可以计算出事件经历的精确时间。测试函数SLEEP(100)的精确持续时间方法:
LARGE_INTEGER litmp;
LONGLONG qt1,qt2;
double dft,dff,dfm;
QueryPerformanceFrequency(&litmp);//获得时钟频率
dff=(double)litmp.QuadPart;
QueryPerformanceCounter(&litmp);//获得初始值
qt1=litmp.QuadPart;Sleep(100);
QueryPerformanceCounter(&litmp);//获得终止值
qt2=litmp.QuadPart;
dfm=(double)(qt2-qt1);
dft=dfm/dff;//获得对应的时间值
需要注意的是DFT计算的结果单位是秒。
Qt跨平台的Sleep:
void QTest::qSleep(int ms)
{
QTEST_ASSERT(ms > 0);
#ifdef Q_OS_WIN
Sleep(uint(ms));
#else
struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 };
nanosleep(&ts, NULL);
#endif
}