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();        //最后打印一次  

     

  • 相关阅读:
    java模式及其应用场景
    redis配置密码 redis常用命令
    Redis可视化工具Redis Desktop Manager使用
    String类和StringBuffer类的区别
    centos下搭建redis集群
    eclipse maven项目中使用tomcat插件部署项目
    什么是反向代理,如何区别反向与正向代理
    数据库连接池的原理
    归并排序
    asio-kcp源码分析
  • 原文地址:https://www.cnblogs.com/wgwyanfs/p/6877487.html
Copyright © 2011-2022 走看看