1. 程式人生 > >c++中常用的計算程式執行時間的方法

c++中常用的計算程式執行時間的方法

方法1:

計時函式是clock(),而與其相關的資料型別是clock_t(標頭檔案是time.h)。函式定義原型為:clock_t clock(void);

這個函式返回從“開啟這個程式程序”到“程式中呼叫clock()函式”時之間的CPU時鐘計時單元(clock tick)數,在MSDN中稱之為掛鐘時間(wal-clock)。

clock_t是一個長整形數。另外在time.h檔案中,還定義了一個常量CLOCKS_PER_SEC,它用來表示一秒鐘會有多少個時鐘計時單元,因此,我們就可以使用公式clock()/CLOCKS_PER_SEC來計算一個程序自身的執行時間。

給個例子:

  1. #include "stdafx.h"  
  2. #include <time h="">  
  3. #include <iostream>  
  4. using namespace std;  
  5. int _tmain(int argc, _TCHAR* argv[])  
  6. {  
  7.     clock_t start,end;  
  8.     double totaltime;  
  9.     start = clock();  
  10.     ...//程式主程式碼  
  11.     end = clock();  
  12.     totaltime = (double)(end - start)/CLOCKS_PER_SEC;  
  13.     cout<<"程式執行時間為:"<<totaltime<<"秒!"<<endl;  
  14.     return 0;  
  15. }  

方法2:

使用GetTickCount()函式,標頭檔案是<windows.h>,GetTickCount函式返回從系統執行到現在所經歷的時間(型別是DWORD),單位是毫秒,因為DWORD表示範圍的限制,所以系統的執行時間表示不能超過DWORD限制。

給個例子:



  1. #include "stdafx.h"  
  2. #include <windows h="">  
  3. //#include <time h="">  
  4. #include <iostream>  
  5. using namespace std;  
  6. int _tmain(int argc, _TCHAR* argv[])  
  7. {  
  8.     DWORD start = GetTickCount();  
  9.     ...//程式主程式碼  
  10.     DWORD end = GetTickCount();  
  11.     cout<<"程式執行時間為:"<<(end - start)<<"毫秒!"<<endl;  
  12.     return 0;  
  13. }  

方法3:

time_t類,標頭檔案是<ctime>,精確到秒。

給個例子:

  1. #include "stdafx.h"  
  2. //#include <windows h="">  
  3. //#include <time h="">  
  4. #include <ctime>  
  5. #include <iostream>  
  6. using namespace std;  
  7. int _tmain(int argc, _TCHAR* argv[])  
  8. {  
  9.  time_t start = 0,end = 0;  
  10.     time(&start);  
  11.  ...//程式主程式碼  
  12.  time(&end);  
  13.  cout<<"程式執行時間為:"<<(end - start)<<"秒!"<<endl;  
  14.  return 0;  
  15. }