Windows 各種計時函式總結
標準C/C++的二個計時函式time()及clock()
time_t time
返回以格林尼治時間(GMT)為標準,從1970年1月1日00:00:00到現在的此時此刻所經過的秒數。
time_t實際是個long長整型typedef long time_t;
標頭檔案:#include <time.h>
clock_t clock(void);
返回程序啟動到呼叫函式時所經過的CPU時鐘計時單元(clock tick)數,在MSDN中稱之為掛鐘時間(wal-clock),以毫秒為單位。
clock_t實際是個long長整型typedef long clock_t;
標頭檔案:#include <time.h>
Windows系統API函式
timeGetTime()、GetTickCount()及QueryPerformanceCounter()
DWORD timeGetTime(VOID);
返回系統時間,以毫秒為單位。系統時間是從系統啟動到呼叫函式時所經過的毫秒數。注意,這個值是32位的,會在0到2^32之間迴圈,約49.71天。
標頭檔案:#include <Mmsystem.h>
引用庫:#pragma comment(lib, "Winmm.lib")
DWORD WINAPI GetTickCount(void);
這個函式和timeGetTime()一樣也是返回系統時間,以毫秒為單位。
標頭檔案:直接使用#include <windows.h>就可以了。
高精度計時,以微秒為單位(1毫秒=1000微秒)。
先看二個函式的定義
BOOL QueryPerformanceCounter(LARGE_INTEGER *lpPerformanceCount);
得到高精度計時器的值(如果存在這樣的計時器)。
BOOL QueryPerformanceFrequency(LARGE_INTEGER *lpFrequency);
返回硬體支援的高精度計數器的頻率(次每秒),返回0表示失敗。
再看看LARGE_INTEGER
它其實是一個聯合體,可以得到__int64 QuadPart;也可以分別得到低32位DWORD LowPart和高32位的值LONG HighPart。
在使用時,先使用QueryPerformanceFrequency()得到計數器的頻率,再計算二次呼叫QueryPerformanceCounter()所得的計時器值之差,用差去除以頻率就得到精確的計時了。
標頭檔案:直接使用#include <windows.h>就可以了。
下面給出示例程式碼,可以在你電腦上測試下。
//Windows系統下time(),clock(),timeGetTime(),GetTickCount(),QueryPerformanceCounter()來計時 by MoreWindows
#include <stdio.h>
#include <windows.h>
#include <time.h> //time_t time() clock_t clock()
#include <Mmsystem.h> //timeGetTime()
#pragma comment(lib, "Winmm.lib") //timeGetTime()
int main()
{
//用time()來計時 秒
time_t timeBegin, timeEnd;
timeBegin = time(NULL);
Sleep(1000);
timeEnd = time(NULL);
printf("%d\n", timeEnd - timeBegin);
//用clock()來計時 毫秒
clock_t clockBegin, clockEnd;
clockBegin = clock();
Sleep(800);
clockEnd = clock();
printf("%d\n", clockEnd - clockBegin);
//用timeGetTime()來計時 毫秒
DWORD dwBegin, dwEnd;
dwBegin = timeGetTime();
Sleep(800);
dwEnd = timeGetTime();
printf("%d\n", dwEnd - dwBegin);
//用GetTickCount()來計時 毫秒
DWORD dwGTCBegin, dwGTCEnd;
dwGTCBegin = GetTickCount();
Sleep(800);
dwGTCEnd = GetTickCount();
printf("%d\n", dwGTCEnd - dwGTCBegin);
//用QueryPerformanceCounter()來計時 微秒
LARGE_INTEGER large_interger;
double dff;
__int64 c1, c2;
QueryPerformanceFrequency(&large_interger);
dff = large_interger.QuadPart;
QueryPerformanceCounter(&large_interger);
c1 = large_interger.QuadPart;
Sleep(800);
QueryPerformanceCounter(&large_interger);
c2 = large_interger.QuadPart;
printf("本機高精度計時器頻率%lf\n", dff);
printf("第一次計時器值%I64d 第二次計時器值%I64d 計時器差%I64d\n", c1, c2, c2 - c1);
printf("計時%lf毫秒\n", (c2 - c1) * 1000 / dff);
printf("By MoreWindows\n");
return 0;
}
下面是本人電腦上的測試結果:
轉載請標明出處,原文地址:http://blog.csdn.net/morewindows/article/details/6854764
再分享一下我老師大神的人工智慧教程吧。零基礎!通俗易懂!風趣幽默!希望你也加入到我們人工智慧的隊伍中來!http://www.captainbed.net