第一种:使用 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;
}