先上代码:
#include <Windows.h>
/** @class CFuncTimeTestter
* @brief 函数执行时间测试器
*/
class CFuncTimeTestter
{
public:
explicit CFuncTimeTestter(const std::string& moduleName="", const std::string& testName = "")
: m_testName(testName),
m_moduleName(moduleName)
{
QueryPerformanceCounter(&m_begintime);
QueryPerformanceFrequency(&m_frequency);
};
~CFuncTimeTestter()
{
QueryPerformanceCounter(&m_endtime);
your_log_print(m_moduleName.c_str(), "%s 执行完成,耗时%dms", m_testName.c_str(), (m_endtime.QuadPart-m_begintime.QuadPart)*1000 / m_frequency.QuadPart);
};
private:
std::string m_testName;
std::string m_moduleName;
LARGE_INTEGER m_frequency;
LARGE_INTEGER m_begintime;
LARGE_INTEGER m_endtime;
};
耗时统计类使用了windows的高精度性能计数函数,我们来看看QueryPerformanceCounter的介绍:
函数QueryPerformanceCounter用于得到高精度计时器的值(如果存在这样的计时器)
BOOL QueryPerformanceCounter(LARGE_INTEGER *ipPerformanceCount);//参数指向计数器的值
参数LARGE_INTEGER *ipProformanceCount
为一个指针变量用于函数传值,即指向现时计数器的值.如果安装的硬件不支持高精度计时器,该参数将返回0,
关于返回值:
如果安装的硬件支持高精度计时器,函数将返回非0值.
如果安装的硬件不支持高精度计时器,函数将返回0.
)
为使用方便,再定义一个方便的宏,供使用:
#define PRINT_COST_TIME CFuncTimeTestter timeTester("TimeTest", __FUNCTION__);
函数执行完毕,会答应当前函数名,并输出其执行时间。