// Windows API in winbase.h
Code
//
// Performance counter API's
//
WINBASEAPI
BOOL
WINAPI
QueryPerformanceCounter(
__out LARGE_INTEGER *lpPerformanceCount
);
WINBASEAPI
BOOL
WINAPI
QueryPerformanceFrequency(
__out LARGE_INTEGER *lpFrequency
);
// PerfTimer.h
Code
#ifdef _DEBUG
#define TraceFnTime(szFunctionName) DebugTimer aTimer(szFunctionName)
#else
#define TraceFnTime(szFunctionName)
#endif
//////////////////////////////////////////////////////////////////////////
// using the difference of the CPU tick count to divide the CPU frequency per second
// time_span = (difference of CPU tick count) / (CPU frequency) : (seconds)
//////////////////////////////////////////////////////////////////////////
class AFX_EXT_CLASS CPerfTimer
{
private:
LARGE_INTEGER m_liFreq;
LARGE_INTEGER m_liStart;
LARGE_INTEGER m_liEnd;
public:
CPerfTimer(void)//: //m_liFreq.QuadPart(0)//, m_liStart.QuadPart(0), m_liEnd.QuadPart(0)
{
QueryPerformanceFrequency(&m_liFreq); // cpu頻率
}
~CPerfTimer(void)
{};
public:
inline void Start()
{
QueryPerformanceCounter(&m_liStart); // 開始計時的cpu tick
}
inline void Stop()
{
QueryPerformanceCounter(&m_liEnd); // 計時結束的cpu tick
};
inline double GetTimeSpan() // time unit is second
{
return (double)(m_liEnd.QuadPart - m_liStart.QuadPart)/(double)m_liFreq.QuadPart;
}
};
// 利用臨時對象的構造和析構對統計函數已耗用時間
class AFX_EXT_CLASS DebugTimer
{
public:
explicit DebugTimer(LPCTSTR lpszFuncName)
:m_szFunction(lpszFuncName)
{
m_thePerfTimer.Start();
}
~DebugTimer()
{
m_thePerfTimer.Stop();
// 列印到output
TRACE2("%s: %.12f\r\n", m_szFunction, m_thePerfTimer.GetTimeSpan());
}
private:
CPerfTimer m_thePerfTimer;
LPCTSTR m_szFunction;
};