计算程序运行时间的封装

 

只能在linux下使用:

#include <sys/time.h>

class timer
{
    public:
        timer(int _timerType = CLOCK_PROCESS_CPUTIME_ID) : timerType(_timerType)
        {
            clock_gettime(timerType, &begin);
        }
        long elapsed() const
        {
            timespec end;
            clock_gettime(timerType, &end);
            timespec temp;
            if ((end.tv_nsec-begin.tv_nsec)<0) {
                temp.tv_sec = end.tv_sec-begin.tv_sec-1;
                temp.tv_nsec = 1000000000+end.tv_nsec-begin.tv_nsec;
            } else {
                temp.tv_sec = end.tv_sec-begin.tv_sec;
                temp.tv_nsec = end.tv_nsec-begin.tv_nsec;
            }
            return temp.tv_sec*1000*1000*1000 + temp.tv_nsec;
        }
        void restart()
        {
             clock_gettime(timerType, &begin);
        }
    private:
        timespec begin;
        int timerType;
};

链接时需要 -lrt

使用如下:

timer t;
int *pi = new int;
std::cout<<t.elapsed()<<std::endl;

t.restart();
char *pc = new char[3];
std::cout<<t.elapsed()<<std::endl;

 

测试函数输出时间:

#include <sys/time.h>
#include <string>
#include <iostream>

class scoped_timer
{
    public:
        scoped_timer(std::string _funName = "", int _timerType = CLOCK_PROCESS_CPUTIME_ID) : funName(_funName),timerType(_timerType)
        {
            clock_gettime(timerType, &begin);
        }
        ~scoped_timer()
        {
            std::cout<<funName<<" : "<<elapsed()<<"(ms)"<<std::endl;  //这里也可以输出到文件
        }
        private:
            long elapsed() const
            {
                timespec end;
                clock_gettime(timerType, &end);
                timespec temp;
                if ((end.tv_nsec-begin.tv_nsec)<0) {
                    temp.tv_sec = end.tv_sec-begin.tv_sec-1;
                    temp.tv_nsec = 1000000000+end.tv_nsec-begin.tv_nsec;
                } else {
                    temp.tv_sec = end.tv_sec-begin.tv_sec;
                    temp.tv_nsec = end.tv_nsec-begin.tv_nsec;
                }
                return temp.tv_sec*1000*1000*1000 + temp.tv_nsec;
            }
    private:
        timespec begin;
        int timerType;
        std::string funName;
};
#ifdef DEBUG
#define funTime(funname) scoped_timer t(funname);
#else
#define funTime(funname)
#endif

测试程序如下:

void fun()
{
    funTime("fun()");
    for(int i = 0; i < 1000000; i++)
        int *pi = new int;
}

编译时使用:g++ test6.cpp -o test6 -lrt -DDEBUG  执行后就会输出函数消耗时间

 

 

 

 

posted @ 2013-09-04 14:29  轻典  阅读(483)  评论(0编辑  收藏  举报