c++中常用的計算程式執行時間的方法
阿新 • • 發佈:2019-02-05
方法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來計算一個程序自身的執行時間。
給個例子:
- #include "stdafx.h"
- #include <time h="">
- #include <iostream>
- using namespace std;
- int _tmain(int argc, _TCHAR* argv[])
- {
- clock_t start,end;
- double totaltime;
- start = clock();
- ...//程式主程式碼
- end = clock();
- totaltime = (double)(end - start)/CLOCKS_PER_SEC;
- cout<<"程式執行時間為:"<<totaltime<<"秒!"<<endl;
- return 0;
- }
方法2:
使用GetTickCount()函式,標頭檔案是<windows.h>,GetTickCount函式返回從系統執行到現在所經歷的時間(型別是DWORD),單位是毫秒,因為DWORD表示範圍的限制,所以系統的執行時間表示不能超過DWORD限制。
給個例子:
- #include "stdafx.h"
- #include <windows h="">
- //#include <time h="">
- #include <iostream>
- using namespace std;
- int _tmain(int argc, _TCHAR* argv[])
- {
- DWORD start = GetTickCount();
- ...//程式主程式碼
- DWORD end = GetTickCount();
- cout<<"程式執行時間為:"<<(end - start)<<"毫秒!"<<endl;
- return 0;
- }
方法3:
time_t類,標頭檔案是<ctime>,精確到秒。
給個例子:
- #include "stdafx.h"
- //#include <windows h="">
- //#include <time h="">
- #include <ctime>
- #include <iostream>
- using namespace std;
- int _tmain(int argc, _TCHAR* argv[])
- {
- time_t start = 0,end = 0;
- time(&start);
- ...//程式主程式碼
- time(&end);
- cout<<"程式執行時間為:"<<(end - start)<<"秒!"<<endl;
- return 0;
- }