[cpp]%20view%20plain%20copy%20<span style="font-size:14px;"><span style="font-size:18px;">#include<iostream> #include<time.h> using namespace std; int main() { clock_t startTime,endTime; startTime = clock(); for (int i = 0; i < 1000000; i++) { i++; } endTime = clock(); cout << "Totle Time : " <<(double)(endTime - startTime) / CLOCKS_PER_SEC << "s" << endl; system("pause"); return 0; }</span></span> [cpp]%20view%20plain%20copy%20<span style="font-size:14px;">#include<iostream> #include<time.h> using namespace std; int main() { for (int i = 0; i < 1000000; i++) { i++; } cout << "Totle Time : " << (double)clock() /CLOCKS_PER_SEC<< "s" << endl; system("pause"); return 0; }</span>
方法二:GetTickCount()函數:
GetTickCount是函數。GetTickCount返回(retrieve)從操作系統啟動所經過(elapsed)的毫秒數,它的返回值是DWord。函數原型:DWORD%20GetTickCount(void);頭文件:C/C++頭文件:winbase.hwindows程序設計中可以使用頭文件windows.h測試代碼:[cpp]%20view%20plain%20copy%20<span style="font-size:14px;">#include<iostream> #include<Windows.h> using namespace std; int main() { DWORD start_time = GetTickCount(); for (int i = 0; i < 100000000; i++) { i++; } DWORD end_time = GetTickCount(); cout << "The run time is:" << (end_time - start_time) << "ms!" << endl; system("pause"); return 0; }</span> 注意事項: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()函數。