C++記錄精確時間-QueryPerformanceFrequency()

來源:互聯網
上載者:User

精確擷取時間

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");

}

結果為

0.999982

1.000088

1.000200

單位為妙,乘1000000即為微秒

------------------------------------------------------------------------

一個MyTimer類及使用

//MyTimer.h

#ifndef MYTIMER_H#define MYTIMER_H#include <windows.h>class MyTimer{private:LONGLONG _freq;LARGE_INTEGER _begin;LARGE_INTEGER _end;public:long costTime;            // 花費的時間(精確到微秒)public:MyTimer(){LARGE_INTEGER tmp;QueryPerformanceFrequency(&tmp);_freq=tmp.QuadPart;costTime=0;}void Start()            // 開始計時{QueryPerformanceCounter(&_begin);}void End()                // 結束計時{QueryPerformanceCounter(&_end);costTime=(long)((_end.QuadPart - _begin.QuadPart)*1000000/_freq);}void Reset()            // 計時清0{costTime = 0;}};#endif

//MyTimer.cpp

#include "stdafx.h"#include "MyTimer.h"#include <iostream>using namespace std;int _tmain(int argc, _TCHAR* argv[]){int i=10000;MyTimer mt;mt.Start();while((i--)>0);mt.End();cout<<"所用時間為 "<<mt.costTime<<"us"<<endl;return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.