1. 程式人生 > >程序時間測試

程序時間測試

方法 包含 cloc bsp stream 不能 限制 ati str

第一種:使用GetTickCount函數

#include<iostream>
#include<windows.h>

int main()
{
DWORD start_time=GetTickCount();
{
//此處為被測試代碼
}
DWORD end_time=GetTickCount();
cout<<"The run time is:"<<(end_time-start_time)<<"ms!"<<endl;//輸出運行時間
return 0;
}

GetTickCount類型為DWORD,單位為ms,因為DWORD表示範圍的限制,所以使用此種方法存在限制,

即系統的運行時間的ms表示不能超出DWORD的表示範圍。

第二種:使用clock()函數
#include<iostream>
#include<time.h>

int main()
{
clock_t start_time=clock();

{
//被測試代碼
}

clock_t end_time=clock();
cout<< "Running time is: "<<static_cast<double>(end_time-start_time)/CLOCKS_PER_SEC*1000<<"ms"<<endl;//輸出運行時間
return 0;
}

clock()返回從程序運行時刻開始的時鐘周期數,類型為long.

CLOCKS_PER_SEC定義了每秒鐘包含多少了時鐘單元數,因為計算ms,所*1000。

2比1好;

程序時間測試