C++測函數執行時間

析構自動獲取時間

#ifndef TIMESTRAMP_H
#define TIMESTRAMP_H

#include <stdio.h>
#include <iostream>

#ifndef _WIN32
#include <sys/time.h>
#else
#include <windows.h>
#endif

using namespace std;

#define TIME_DEBUG(str) \
	cout <<  "[" << __DATE__ "] data:" << str << endl

#ifndef _WIN32
class timestramp{
public:
    timestramp()
    {
         gettimeofday(&tpstart,NULL);
    }

    ~timestramp()
    {
         gettimeofday(&tpend,NULL);
		 dwTime = 1000000*(tpend.tv_sec- tpstart.tv_sec)+(tpend.tv_usec- tpstart.tv_usec);
         TIME_DEBUG("used time:%ld us\n", dwTime);
    }
private:
     struct timeval tpstart,tpend;
     double timeuse;
	 unsigned long dwTime;
};

#else

class timestramp{
private:
    LARGE_INTEGER m_litmp;
    LONGLONG QPart2;
    LONGLONG QPart1;
    double dfMinus, dfFreq, dfTim;
	static double m_dTimeCount;
public:
    timestramp(){
        QueryPerformanceFrequency(&m_litmp);
        dfFreq = (double)m_litmp.QuadPart;
        QueryPerformanceCounter(&m_litmp);
        QPart1 = m_litmp.QuadPart;
    }

    ~timestramp(){
        QueryPerformanceCounter(&m_litmp);
        QPart2 = m_litmp.QuadPart;
        dfMinus = (double)(QPart2 - QPart1);
        dfTim = dfMinus / dfFreq * 1000;

        //顯示時間
        std::string msg4 = "time:", msg3, msg5 = "ms";
		char strTime[20] = "";
		sprintf(strTime, "%.6lf", dfTim);
		msg3 = strTime;
		msg4 += msg3;
		msg4 += msg5;
		TIME_DEBUG(msg4.c_str());
    }
};
#endif

#endif // TIMESTRAMP_H

使用時
 

#include "timestramp.h"

int main(int argc, char* argv[])
{
    int cnt = 0;
    {
        timestramp ti;
        while(cnt < 1000)
        {
            cnt++;
        }
    }
    getchar();
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章