QueryPerformanceFrequency用法
精确获取时间:
QueryPerformanceFrequency() - 基本介绍
类型:Win32API
原型:BOOL QueryPerformanceFrequency(LARGE_INTEGER *lpFrequency);
作用:返回硬件支持的高精度计数器的频率。
返回值:非零,硬件支持高精度计数器;零,硬件不支持,读取失败。
QueryPerformanceFrequency() - 技术特点
供WIN9X使用的高精度定时器:QueryPerformanceFrequency()和QueryPerformanceCounter(),要求计算机从硬件上支持高精度定时器。需包含windows.h头文件。
函数的原形是:
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的精确时间:
#include <stdio.h>
#include <windows.h>
void main()
{
LARGE_INTEGER nFreq;
LARGE_INTEGER nBeginTime;
LARGE_INTEGER nEndTime;
double time;
QueryPerformanceFrequency(&nFreq);
QueryPerformanceCounter(&nBeginTime);
Sleep(1000);
QueryPerformanceCounter(&nEndTime);
time=(double)(nEndTime.QuadPart-nBeginTime.QuadPart)/(double)nFreq.QuadPart;
printf("%f\n",time);
Sleep(1000);
system("Pause");
}
以上转自: http://www.cppblog.com/deane/articles/113151.html再给出我写的一个Fibonacci的例子:
#include <iostream> #include <cmath> #include <ctime> #include <windows.h> #include<iomanip> using namespace std; unsigned long Fib1(unsigned long n) { return (n == 1 || n == 2) ? 1 : Fib1(n - 1) + Fib1(n - 2); } unsigned long Fib2(unsigned long n) { if (n == 1 || n == 2) { return 1; } unsigned long m1 = 1, m2 = 1; for (unsigned long i = 3; i <= n; i++) { m2 = m1 + m2; m1 = m2 - m1; } return m2; } int main() { LARGE_INTEGER nFreq; LARGE_INTEGER nBeginTime; LARGE_INTEGER nEndTime; double time1 = 0, time2 = 0; unsigned long result1 = 0; unsigned long result2 = 0; unsigned long fib_num = 45; cout.precision(10); cout.setf(cout.showpoint); //设置为始终输出小数点后的数字,就是说 a = 3,它也输出 3.00000 这 QueryPerformanceFrequency(&nFreq); QueryPerformanceCounter(&nBeginTime); result1 = Fib1(fib_num); QueryPerformanceCounter(&nEndTime); time1=(double)(nEndTime.QuadPart-nBeginTime.QuadPart)/(double)nFreq.QuadPart; cout<<"Fib1: "<< fixed<<setprecision(8)<<setiosflags(ios::showpoint)<<time1<<endl; QueryPerformanceFrequency(&nFreq); QueryPerformanceCounter(&nBeginTime); result2 = Fib2(fib_num); QueryPerformanceCounter(&nEndTime); time2=(double)(nEndTime.QuadPart-nBeginTime.QuadPart)/(double)nFreq.QuadPart; cout<<"Fib2: "<< fixed<<setprecision(20)<<setiosflags(ios::showpoint)<<time2<<endl; cout<<"Fib2 cost "<<time2*(unsigned long)100/time1<<"% time of Fib1."<<endl; //cout << "Hello world!" << endl; return 0; }