运行时间是程序的重要性能指标之一,到目前为止,除了调试工具之外,在c++还没有统计程序运行时间的接口,先将我查阅相关资料总结的一个统计程序运行时间的框架总结如下,并附上一个小例子。
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
double start,end;
float duration;
//......
start=clock();//起始时间统计,以时钟数为计量单位
//......
end=clock();//结束时间统计
duration=(end-start)/CLOCKS_PER_SEC;//实际持续时间
//......
return 0;
}
例子如下:
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<ctime>
#include<vector>
using namespace std;
void sleep(clock_t wait_time);
class Test_class
{
private:
int id;
public:
Test_class():id(0){}
virtual ~Test_class(){}
};
int main()
{
double start,end;
float duration;
long loop_num=10000000L;
vector<Test_class*> vec_ptr;
cout<<"sleep for three seconds"<<endl;
sleep((clock_t)3*CLOCKS_PER_SEC);
cout<<"after the sleep"<<endl;
start=clock();
for(long i=loop_num;i>=0;--i);
vec_ptr.push_back(new Test_class());
end=clock();
duration=(end-start)/CLOCKS_PER_SEC;
cout<<"create "<<loop_num<<" of the Test_class objects need "<<duration<<" seconds"<<endl;
return 0;
}
void sleep(clock_t wait_time)
{
clock_t goal;
goal=clock()+wait_time;
while(goal>clock());
}