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();
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

telllong

你的鼓励是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值