c++程序运行时间统计初探

      运行时间是程序的重要性能指标之一,到目前为止,除了调试工具之外,在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());
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值