[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()函數(shù):
GetTickCount是函數(shù)。GetTickCount返回(retrieve)從操作系統(tǒng)啟動(dòng)所經(jīng)過(guò)(elapsed)的毫秒數(shù),它的返回值是DWord。函數(shù)原型:DWORD%20GetTickCount(void);頭文件:C/C++頭文件:winbase.hwindows程序設(shè)計(jì)中可以使用頭文件windows.h測(cè)試代碼:[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> 注意事項(xiàng):GetTickcount函數(shù):它返回從操作系統(tǒng)啟動(dòng)到當(dāng)前所經(jīng)過(guò)的毫秒數(shù),常常用來(lái)判斷某個(gè)方法執(zhí)行的時(shí)間,其函數(shù)原型是DWORD GetTickCount(void),返回值以32位的雙字類(lèi)型DWORD存儲(chǔ),因此可以存儲(chǔ)的最大值是(2^32-1) ms約為49.71天,因此若系統(tǒng)運(yùn)行時(shí)間超過(guò)49.71天時(shí),這個(gè)數(shù)就會(huì)歸0,MSDN中也明確的提到了:"Retrieves the number of milliseconds that have elapsed since the system was started, up to 49.7 days."。因此,如果是編寫(xiě)服務(wù)器端程序,此處一定要萬(wàn)分注意,避免引起意外的狀況。特別注意:這個(gè)函數(shù)并非實(shí)時(shí)發(fā)送,而是由系統(tǒng)每18ms發(fā)送一次,因此其最小精度為18ms。當(dāng)需要有小于18ms的精度計(jì)算時(shí),應(yīng)使用StopWatch方法進(jìn)行。用clock()函數(shù)計(jì)算運(yùn)行時(shí)間,表示范圍一定大于GetTickCount()函數(shù),所以,建議使用clock()函數(shù)。