zoukankan      html  css  js  c++  java
  • C/C++写得一个计时器用于检查程序的处理数据性能

    一般设计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_*/


    调用方式例如以下:

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

     

  • 相关阅读:
    linux虚拟机上网
    asp 两种方法连接sql sever 并显示
    了解ado.net 的相关内库--读书笔记
    win10固态硬盘分区方法
    sql sever2012安装错误,无效的十六进制字符
    python学习笔记3
    python 学习笔记4
    python学习笔记2
    20189319《网络攻防》第十周作业
    20189319《网络攻防》第九周作业
  • 原文地址:https://www.cnblogs.com/wgwyanfs/p/6877487.html
Copyright © 2011-2022 走看看