【C++学习笔记】获取函数运行时间的两种方法

1.GetTickCount()

GetTickCount是windows下的API函数,检索自系统启动以来经过的毫秒数,最多为49.7天。

//头文件
#include <windows.h>
//函数原型
DWORD WINAPI GetTickCount(void);
//返回值:
    系统启动后经过的毫秒数。

测试代码:

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

using namespace std;

void Fun()
{
    for (int i = 1; i < 100000000; ++i)
    {
        ;
    }
}

int main()
{
    DWORD begin = 0;
    DWORD end = 0;
    DWORD  time = 0;

    begin = GetTickCount();
    Fun();
    end = GetTickCount();

    time = (end - begin);                   //ms

    cout << end - begin << endl;

    system("pause");
    return 0;
}

2.Clock()

Clock()是C++库里函数,它返回程序启动后经过的时钟节拍数,CLOCKS_PER_SEC这个宏扩展为一个表达式,表示一秒钟内时钟节拍数,由函数时钟返回。用这个表达式除以时钟节拍数就得到秒数。也有的地方用的时CLK_TCK,它们有同样的功能,不过是这个宏的一个过时的别名。

//头文件
#include <ctime>
//函数原型
clock_t clock ( void );
//返回值
    自程序启动以来,时钟滴答数一直在增加。
    在失败时,函数返回-1的值。
    clock_t是在中定义的一种类型,可以表示时钟滴答数并支持算术运算(通常是长整数)。

代码如下:

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

using namespace std;

void Fun()
{
    for (int i = 1; i < 100000000; ++i)
    {
        ;
    }
}

int main()
{
    int begin = 0;
    int end = 0;
    double time = 0;

    begin = clock();
    Fun();
    end = clock();

    time = (end - begin) / CLOCKS_PER_SEC;

    cout << end - begin << endl;                //s
    cout << CLOCKS_PER_SEC << endl;
    cout << time << endl;

    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/LYJwonderful/article/details/80661771