码迷,mamicode.com
首页 > 编程语言 > 详细

C/C++写得一个计时器用于检查程序的处理数据性能

时间:2015-03-18 12:22:57      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:c++   性能检查   

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

  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_*/  
 

 

调用方式如下:

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

 

C/C++写得一个计时器用于检查程序的处理数据性能

标签:c++   性能检查   

原文地址:http://blog.csdn.net/nyist327/article/details/44408285

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!