1. 程式人生 > >C/C++獲取程式執行時間的五個方法對比

C/C++獲取程式執行時間的五個方法對比

五種獲取C/C++程式執行時間的方法對比如下:

核心函式                                   標頭檔案      函式庫      精度     準確度
QueryPerformanceCounter    windows.h      API        us       非常準確
GetTickTount                         windows.h      API        ms       準確
clock                                         time.h         C函式      ms      較準確
time                                          time.h          C函式       s        很準確
ftime                                      sys/timeb.h    C函式       ms      較準確

在windows平臺下建議使用GetTickCount,當對精度和準確度要求高可以用QueryPerformanceCounter,Linux平臺下建議使用ftime,本程式均在windows平臺下執行,五種獲取程式執行時間的程式碼如下:

#include <iostream>
#include <fstream>
#include <ctime>
#include <windows.h>
#include <tchar.h>
#include <sys/timeb.h>
#include <time.h>
#include <cmath>
#include <stdio.h>

using namespace std;

/**************************獲取系統時間*************************/
void MyGetSystemTime()
{
	SYSTEMTIME currentTime;
	GetSystemTime(¤tTime);
	printf("time: %u/%u/%u %u:%u:%u:%u %d\n", 
		currentTime.wYear,currentTime.wMonth,currentTime.wDay, 
		currentTime.wHour,currentTime.wMinute,currentTime.wSecond, 
		currentTime.wMilliseconds,currentTime.wDayOfWeek);
}

/****************自己實現的定時器,要比Sleep準確****************/
void MySleep(DWORD dwMilliseconds)
{
	LARGE_INTEGER litmp;
	LONGLONG QPart1;
	QueryPerformanceCounter(&litmp);
	QPart1 = litmp.QuadPart;//獲得初始值

	LONGLONG QPart2;
	double dfMinus, dfFreq, dfTim;
	QueryPerformanceFrequency(&litmp);
	dfFreq = (double)litmp.QuadPart;//獲得計數器的時鐘頻率

	do
	{
		QueryPerformanceCounter(&litmp);
		QPart2 = litmp.QuadPart;//獲得中止值
		dfMinus = (double)(QPart2-QPart1);
		dfTim = dfMinus / dfFreq * 1000;//獲得對應的時間值,單位為毫秒
	}while(dfTim < dwMilliseconds);
}

int main()
{
/**************QueryPerformanceCounter(),windows.h,API,us****************///精度最高
	 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);

/**************GetTickCount(),windows.h,API,ms****************///首選
	DWORD start, end;
	start = GetTickCount();
	MySleep(1000);
	end = GetTickCount();
	printf("time: %d ms\n", end - start);

/**************clock(),time.h,C函式,ms,不太準****************/
	clock_t start, end;
	start = clock();
	Sleep(1000);
	end = clock();
	printf("time: %d ms\n", end - start);

/**************time(),time.h,C函式,s****************/
	time_t start, end;
	start = time(NULL);
	Sleep(1000);
	end = time(NULL);
	printf("time: %d ms\n", end - start);

/**************ftime(),sys/timeb.h,C函式,ms,不太準****************/
	struct timeb startTime , endTime;
	ftime(&startTime);
	Sleep(1000);
	ftime(&endTime);
	printf("time: %d ms\n", (endTime.time-startTime.time)*1000 + (endTime.millitm - startTime.millitm));

	return 0;
}