利用Windows API实现精确计时


// Windows API in winbase.h
//
// Performance counter API's
//

WINBASEAPI
BOOL
WINAPI
QueryPerformanceCounter(
        __out LARGE_INTEGER *lpPerformanceCount
        );

WINBASEAPI
BOOL
WINAPI
QueryPerformanceFrequency(
        __out LARGE_INTEGER *lpFrequency
        );

// PerfTimer.h
#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;
};

本文出自 “dlbrant” 博客,转载请与作者联系!

你可能感兴趣的:(windows,timer,api,debug,performance)