纵他(C++)虐我一遍后,我任带她如初恋----获取一个函数的运行时间

//没有使用GetTikCount函数

#define _CRT_SECURE_NO_WARNINGS

#include <iostream>
#include <time.h>
using namespace std;
int main()
{

clock_t start_time = clock();

     //代码段

{
int i = 0;
while(i<1000000000)
{
i++;
}

}

//代码段结束

clock_t end_time = clock();
cout<<"Runing time is:"<<static_cast<double>(end_time - start_time)/CLOCKS_PER_SEC*1000<<"ms"<<endl;
return 0;
}
//clock_t,clock()定义于time.h中,clock()返回从程序运行时刻开始的时钟周期数,类型为long.CLOCKS_PER_SEC定义了每秒钟包含多少了时钟单元数,因为计算ms,所以*1000。
//1000000000      Runing time is:2511ms

//100000000       Runing time is:312ms;   每次执行时间可能不一样


//使用GetTickCount()函数

#include <iostream>
#include <Windows.h>
using namespace std;
int main()
{

DWORD start_time = GetTickCount();

//代码段

{
int i = 0;
while(i<1000000000)
{
i++;
}

}

//代码段

DWORD end_time = GetTickCount();
cout<<"Runing time is:"<<(end_time - start_time)<<"ms"<<endl;
return 0;
}
//1000000000      Runing time is:2465ms
//100000000       Runing time is:265ms; 
//
//用clock()函数计算运行时间,表示范围一定大于GetTickCount()函数,所以,建议使用clock()函数。

猜你喜欢

转载自blog.csdn.net/weixin_42119299/article/details/80679543