第一種:使用 GetTickCount()
函數
該函數返回從系統運行到現在所經歷的時間,返回類型爲 DWORD,是unsigned long 的別名,單位爲ms。
#include <iostream>
#include <windows.h>
void TestFun()
{
// 測試函數...
}
int main()
{
DWORD start_time = GetTickCount();
TestFun();
DWORD end_time = GetTickCount();
cout << "函數共用時:" << end_time - start_time << "ms" << endl;
return 0;
}
第二種:使用 clock()
函數
函數返回從程序運行時刻開始的時鐘週期數,類型爲 long,宏 CLOCKS_PRE_SEC
定義了每秒包含了多少時鐘單位,不同系統下該宏可能不一致。如果需要獲取秒數需要(end-start)/CLOCKS_PRE_SEC。
#include <iostream>
#include <time.h>
void TestFun()
{
// 測試函數...
}
int main()
{
clock_t start = clock();
TestFun();
clock_t end = clock();
cout << "函數共用時:" << (end-start)/CLOCKS_PRE_SEC << "s" << endl;
return 0;
}