對Windows平台下常用的計時函數進行總結,包括精度為秒、毫秒、微秒三種精度的5 種方法。分為在標准C/C++下的二種time()及clock(),標准C/C++所以使用的time()及clock()不僅可以用在Windows 系統,也可以用於Linux系統。
在Windows系統下三種,使用Windows提供的API接口timeGetTime()、 GetTickCount()及QueryPerformanceCounter()來完成。
[cpp]
#include <windows.h>
#include <time.h> //time_t time() clock_t clock()
#include <Mmsystem.h> //timeGetTime()
#pragma comment(lib, "Winmm.lib") //timeGetTime()
int main(int argc, char* argv[])
{
//用time()來計時 秒
time_t timeBegin, timeEnd;
timeBegin = time(NULL);
Sleep(800);
timeEnd = time(NULL);
printf("time %d\n", timeEnd - timeBegin);
//用clock()來計時 毫秒
clock_t clockBegin, clockEnd;
clockBegin = clock();
Sleep(800);
clockEnd = clock();
printf("clock %d\n", clockEnd - clockBegin);
//用timeGetTime()來計時 毫秒
DWORD dwBegin, dwEnd;
dwBegin = timeGetTime();
Sleep(800);
dwEnd = timeGetTime();
printf("timeGetTime %d\n", dwEnd - dwBegin);
//用GetTickCount()來計時 毫秒
DWORD dwGTCBegin, dwGTCEnd;
dwGTCBegin = GetTickCount();
Sleep(800);
dwGTCEnd = GetTickCount();
printf("GetTickCount %d\n", dwGTCEnd - dwGTCBegin);
//用QueryPerformanceCounter()來計時 微秒
LARGE_INTEGER large_interger;
double dff;
__int64 c1, c2;
//獲取是否支持精確定時器。 定時器的頻率
if( 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("\n");
}
return 0;
}
#include <windows.h>
#include <time.h> //time_t time() clock_t clock()
#include <Mmsystem.h> //timeGetTime()
#pragma comment(lib, "Winmm.lib") //timeGetTime()
int main(int argc, char* argv[])
{
//用time()來計時 秒
time_t timeBegin, timeEnd;
timeBegin = time(NULL);
Sleep(800);
timeEnd = time(NULL);
printf("time %d\n", timeEnd - timeBegin);
//用clock()來計時 毫秒
clock_t clockBegin, clockEnd;
clockBegin = clock();
Sleep(800);
clockEnd = clock();
printf("clock %d\n", clockEnd - clockBegin);
//用timeGetTime()來計時 毫秒
DWORD dwBegin, dwEnd;
dwBegin = timeGetTime();
Sleep(800);
dwEnd = timeGetTime();
printf("timeGetTime %d\n", dwEnd - dwBegin);
//用GetTickCount()來計時 毫秒
DWORD dwGTCBegin, dwGTCEnd;
dwGTCBegin = GetTickCount();
Sleep(800);
dwGTCEnd = GetTickCount();
printf("GetTickCount %d\n", dwGTCEnd - dwGTCBegin);
//用QueryPerformanceCounter()來計時 微秒
LARGE_INTEGER large_interger;
double dff;
__int64 c1, c2;
//獲取是否支持精確定時器。 定時器的頻率
if( 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("\n");
}
return 0;
}