背景:
在参加竞赛或是机试时,常常遇到题目要求你写的算法必须在一定的时间限制内。那么问题来了,怎么计算该个算法的执行时间呢?在我在网上查找了一些资料后,发现一个通用的方法,适用于C/C++。通过这篇文章,把这种简单的思想分享出来。
clock计时函数
clock()是C/C++中的计时函数,而与其相关的数据类型是clock_t。其相关的头文件是<time.h>或<ctime>。其中<time.h>是C语言标准库中的库函数,<ctime>是C++语言std空间中的库函数。
函数原型: clock_t clock(void) ;
- clock_t是数据类型,clock是函数名,参数为空;
- 函数返回:从“开启这个程序进程”到“程序中调用clock()函数”时之间的CPU时钟计时单元(clock tick)数。在MSDN中称之为挂钟时间(wal-clock);若挂钟时间不可取,则返回-1。
- clock_t的数据类型为long型。
- 在time.h文件中,还定义了一个常量CLOCKS_PER_SEC,它用来表示一秒钟会有多少个时钟计时单元,其定义如下:
#define CLOCKS_PER_SEC ((clock_t)1000)
clock函数的初步认识
//clock_t数据类型和clock函数
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
clock_t startTime, endTime;
startTime = clock();
for (int i = 0; i < 1000000; i++)
{
i++;
}
endTime = clock();
cout << "Totle Time : " << (double)(endTime - startTime) / CLOCKS_PER_SEC << "s" << endl;
/*
注意,在DEV-C++中须使用printf才能输出时间:
printf("%lf秒", (double)(endTime - startTime) / CLOCKS_PER_SEC);
*/
return 0;
}
使用示例
# include<iostream>
# include<ctime>
using namespace std;
# define N 10000
clock_t Begin, End; //typedef long clock_t
double duration;
void fun1(int n)//普通输出
{
for (int i = 0; i <= n; i++)
cout << i << endl;
}
void fun2(int n)//递归
{
if (n)
{
fun2(n - 1);
cout << n << endl;
}
else cout << 0 << endl;
}
int main()
{
Begin = clock();//开始计时
//====================start: 这里写要测试的代码===================
fun1(100);
//====================end: 这里写要测试的代码===================
End = clock();//结束计时
duration = double(End - Begin) / CLK_TCK; //duration就是运行函数所打的点数, CLK_TCK是每秒所打点数
cout << "tick=" << double(End - Begin) << endl;
cout << "duration=" << duration <<"s"<< endl;
system("pause");
return 0;
}