C/C++计时器检查程序性能

一般设计C/C++程序需要每秒能处理多少的数据,因此可以做一个简单的计时器来计时,代码如下:

[cpp]  view plain  copy
  1. #ifndef _TIMER_H_  
  2. #define _TIMER_H_  
  3. #include <string>  
  4. #include <sys/time.h>  
  5. using namespace std;  
  6. class Timer{  
  7. private:  
  8.         timeval tstart;  
  9.         timeval tend;  
  10.         unsigned count;  
  11.         unsigned print_count;  
  12. public:  
  13.         Timer():count(0),print_count(10000){  
  14.         }  
  15.         Timer(int pc):count(0),print_count(pc){  
  16.         }  
  17.         void add(){  
  18.                 count++;  
  19.                 if(count % print_count == 0){  
  20.                         end();  
  21.                         begin();  
  22.                 }  
  23.         }  
  24.         void begin(){  
  25.                 gettimeofday(&tstart, NULL);  
  26.         }  
  27.         void end(){  
  28.                 gettimeofday(&tend, NULL);  
  29.                 double linStart = ((double)tstart.tv_sec * 1000000 + (double)tstart.tv_usec);   //unit S  
  30.                 double linEnd = ((double)tend.tv_sec * 1000000 + (double)tend.tv_usec);         //unit S  
  31.                 double delta = (linEnd-linStart)/1000000;                                       //second  
  32.                 printf("Timer:%d %d %f %f/n", print_count,count,delta,print_count/delta);  
  33.         }  
  34. };  
  35. #endif /*_TIMER_H_*/  
 

 

调用方式如下:

[cpp]  view plain  copy
  1. Timer timer(10000); //多少条数据打印一次  
  2. timer.begin();      //开始计时  
  3. for(;;){  
  4. timer.add();        //递增,达到打印数量时打印  
  5. }  
  6. timer.end();        //最后打印一次  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值