第一种:使用 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;
}
本文介绍两种测量函数执行时间的方法:一是使用GetTickCount()函数,它返回系统启动以来的毫秒数;二是使用clock()函数,它返回从程序开始运行到当前的时钟周期数。这些方法有助于评估代码性能。
7万+

被折叠的 条评论
为什么被折叠?



