一、clock()計時函數
clock()是C/C++中的計時函數,而與其相關的數據類型是clock_t。在MSDN中,查得對clock函數定義如下:
clock_t clock(void) ;
簡單而言,就是該程序從啟動到函數調用占用CPU的時間。這個函數返回從“開啟這個程序進程”到“程序中調用clock()函數”時之間的CPU時鍾計時單元(clock tick)數,在MSDN中稱之為掛鍾時間(wal-clock);若掛鍾時間不可取,則返回-1。其中clock_t是用來保存時間的數據類型。
在time.h文件中,我們可以找到對clock_t()的定義:
#ifndef _CLOCK_T_DEFINED
typedef long clock_t;
#define _CLOCK_T_DEFINED
#endif
很明顯,clock_t是一個長整形數。在time.h文件中,還定義了一個常量CLOCKS_PER_SEC,它用來表示一秒鍾會有多少個時鍾計時單元,其定義如下:
#define CLOCKS_PER_SEC ((clock_t)1000)
注:我是用的CodeBlocks查看的定義,需要軟件的請后台留言。
下面來看測試代碼:
1 //計算一段程序運行的時間 2 #include<iostream> 3 #include<ctime> 4 using namespace std; 5 int main() 6 { 7 clock_t startTime,endTime; 8 startTime = clock();//計時開始 9 for (int i = 0; i < 2147483640; i++) 10 { 11 i++; 12 } 13 endTime = clock();//計時結束 14 cout << "The run time is: " <<(double)(endTime - startTime) / CLOCKS_PER_SEC << "s" << endl; 15 system("pause"); 16 return 0; 17 } 18 //注釋在:VC++6.0中可以用CLK_TCK替換CLOCKS_PER_SEC。
1 //計算整個程序運行的時間 2 #include<iostream> 3 #include<time.h> 4 using namespace std; 5 int main() 6 { 7 for (int i = 0; i < 2147483640; i++) 8 { 9 i++; 10 } 11 cout << "The run time is:" << (double)clock() /CLOCKS_PER_SEC<< "s" << endl; 12 system("pause"); 13 return 0; 14 }
兩個寫在一起
1 #include<iostream> 2 #include<ctime> 3 using namespace std; 4 int main() 5 { 6 clock_t startTime,endTime; 7 for (int i = 0; i < 2147483640; i++) 8 { 9 i++; 10 } 11 startTime = clock();//計時開始 12 for ( i = 0; i < 2147483640; i++) 13 { 14 i++; 15 } 16 endTime = clock();//計時結束 17 cout << "The run time is:" <<(double)(endTime - startTime) / CLOCKS_PER_SEC << "s" << endl; 18 cout << "The run time is:" << (double)clock() /CLOCKS_PER_SEC<< "s" << endl; 19 system("pause"); 20 return 0; 21 }
程序運行結果如下:
我用了兩個一樣的for循環,可以看出程序種的運行時間差不多是一個循環的兩倍。
二、GetTickCount()函數
GetTickCount是一種函數。GetTickCount返回(retrieve)從操作系統啟動所經過(elapsed)的毫秒數,它的返回值是DWORD。
函數原型:
DWORD GetTickCount(void);
頭文件:
C/C++頭文件:winbase.h
windows程序設計中可以使用頭文件windows.h
下面來看測試代碼:
1 #include<iostream> 2 #include<Windows.h> 3 using namespace std; 4 int main() 5 { 6 DWORD startTime = GetTickCount();//計時開始 7 for (int i = 0; i < 2147483640; i++) 8 { 9 i++; 10 } 11 DWORD endTime = GetTickCount();//計時結束 12 cout << "The run time is:" << endTime - startTime << "ms" << endl; 13 system("pause"); 14 return 0; 15 }
注意事項:
GetTickcount函數:它返回從操作系統啟動到當前所經過的毫秒數,常常用來判斷某個方法執行的時間,其函數原型是DWORD GetTickCount(void),返回值以32位的雙字類型DWORD存儲,因此可以存儲的最大值是(2^32-1) ms約為49.71天,因此若系統運行時間超過49.71天時,這個數就會歸0,MSDN中也明確的提到了:"Retrieves the number of milliseconds that have elapsed since the system was started, up to 49.7 days."。因此,如果是編寫服務器端程序,此處一定要萬分注意,避免引起意外的狀況。
特別注意:這個函數並非實時發送,而是由系統每18ms發送一次,因此其最小精度為18ms。當需要有小於18ms的精度計算時,應使用StopWatch方法進行。
用clock()函數計算運行時間,表示范圍一定大於GetTickCount()函數,所以,建議使用clock()函數。
兩種函數功能一樣,這就看自己的取舍。
友情鏈接:Java中如何計算程序運行時間——》https://www.cnblogs.com/didiaodidiao/p/9249485.html