Introduction
The motivation for this came when I needed to time sections of code while analyzing performance issues. The existing timers did not provide the necessary granularity to accurately measure execution times in microseconds. So I ended up creating this simple class to do the timing.
Here's the class declaration:
#if !defined(HIGHRESELAPSEDTIMER_H_INCLUDED_)
#define HIGHRESELAPSEDTIMER_H_INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif
#ifdef _DEBUG
class HighResElapsedTimer
{
public:
HighResElapsedTimer(const CString& strName) : m_strName(strName)
{
if (m_llFrequency == 0)
{
LARGE_INTEGER liFrequency;
QueryPerformanceFrequency(&liFrequency);
m_llFrequency = liFrequency.QuadPart;
}
QueryPerformanceCounter(&m_llCounter);
}
virtual ~HighResElapsedTimer()
{
LARGE_INTEGER liNow;
QueryPerformanceCounter(&liNow);
double duration = (double)
(liNow.QuadPart - m_llCounter.QuadPart)/m_llFrequency;
TRACE(_T("%s : Elapsed time = %.3lf microseconds\n"),
m_strName, duration);
}
private:
CString m_strName;
LARGE_INTEGER m_llCounter;
private:
static LONGLONG m_llFrequency;
private:
HighResElapsedTimer(const HighResElapsedTimer&);
HighResElapsedTimer& operator=(const HighResElapsedTimer&);
};
#endif
#endif
... and here is the implementation.
#include "stdafx.h"
#include "HighResElapsedTimer.h"
#ifdef _DEBUG
LONGLONG HighResElapsedTimer::m_llFrequency = 0;
#endif
Since I was timing the code execution only during debug builds, I've guarded the code using #ifdef _DEBUG
's & used TRACE
for output. If you want to time release builds or output differently, it should be fairly trivial to do so.
I've tested this only on NT4 SP6a & hopefully it will work on Win95 m/cs also.