获取函数运行时间的两种方法

来源:互联网 发布:少林足球影评知乎 编辑:程序博客网 时间:2024/05/19 15:25

第一种:使用 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;}
原创粉丝点击