一般设计C/C++程序需要每秒能处理多少的数据,因此可以做一个简单的计时器来计时,代码如下:
[cpp] view
plaincopy
- #ifndef _TIMER_H_
- #define _TIMER_H_
- #include <string>
- #include <sys/time.h>
- using namespace std;
- class Timer{
- private:
- timeval tstart;
- timeval tend;
- unsigned count;
- unsigned print_count;
- public:
- Timer():count(0),print_count(10000){
- }
- Timer(int pc):count(0),print_count(pc){
- }
- 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
- printf("Timer:%d %d %f %f/n", print_count,count,delta,print_count/delta);
- }
- };
- #endif /*_TIMER_H_*/
调用方式如下:
[cpp] view
plaincopy
- Timer timer(10000); //多少条数据打印一次
- timer.begin(); //开始计时
- for(;;){
- timer.add(); //递增,达到打印数量时打印
- }
- timer.end(); //最后打印一次
时间: 2024-10-15 10:19:03