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

来源:互联网 发布:java尚学堂马士兵 编辑:程序博客网 时间:2024/04/27 20:44

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

#ifndef _TIMER_H_  #define _TIMER_H_  #include <string>  #include <fstream>#include <sys/time.h>  using namespace std;  class Timer{  private:        timeval tstart;          timeval tend;          unsigned count;          unsigned print_count;          ofstream output;        void OpenFile();public:          Timer():count(0),print_count(10000){              OpenFile();        }          Timer(int pc):count(0),print_count(pc){              OpenFile();        }          ~Timer(){ output.close(); }        void add(){                  count++;                  if(count % print_count == 0){                          end();                          begin();                  }          }          void begin(){                  gettimeofday(&tstart, NULL);          }          void end(){                  gettimeofday(&tend, NULL);                  double linStart = ((double)tstart.tv_sec * 1000000 + (double)tstart.tv_usec);   //unit S                  double linEnd = ((double)tend.tv_sec * 1000000 + (double)tend.tv_usec);         //unit S                  double delta = (linEnd-linStart)/1000000;                                       //second                  output << "Timer : " << print_count << " " << count << " " << delta << " " << print_count/delta << endl;        }  };  void Timer::OpenFile(){    output.open("timer.txt", ios::ate|ios::out);    if (!output)    {        printf("Create file failed!");        exit(-1);    }    output << "       " << "count" << " " << "total" << " " << "time" << " " << "frequence" << endl;}#endif /*_TIMER_H_*/


调用方式如下:

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

 

0 0
原创粉丝点击