You did not say which operating system you are using. With Windows, the performance counter is the best choice.
Here is a small class using the performance counter that can be used to measure code execution time:
class CMyTimer
{
public:
CMyTimer(bool bStart = false);
bool Start();
double GetElapsedTime() const;
inline DWORD GetElapsedTimeMS() const
{ return static_cast<DWORD>(1E3 * GetElapsedTime()); }
inline void Stop() { m_qwStartTime.QuadPart = 0LL; }
inline bool IsStarted() const { return m_qwStartTime.QuadPart != 0LL; }
inline LONGLONG GetStartTime() const { return m_qwStartTime.QuadPart; }
inline LONGLONG GetFrequency() const { return s_qwPerfFreq.QuadPart; }
protected:
LARGE_INTEGER m_qwStartTime;
private:
static LARGE_INTEGER s_qwPerfFreq;
};
#include "MyTimer.h"
LARGE_INTEGER CMyTimer::s_qwPerfFreq = { 0 };
CMyTimer::CMyTimer(bool bStart )
{
m_qwStartTime.QuadPart = 0LL;
if (bStart)
Start();
}
bool CMyTimer::Start(void)
{
if (0LL == s_qwPerfFreq.QuadPart)
::QueryPerformanceFrequency(&s_qwPerfFreq);
return (0LL != s_qwPerfFreq.QuadPart &&
::QueryPerformanceCounter(&m_qwStartTime));
}
double CMyTimer::GetElapsedTime() const
{
LARGE_INTEGER qwEndTime;
return (IsStarted() && ::QueryPerformanceCounter(&qwEndTime)) ?
static_cast<double>(qwEndTime.QuadPart - m_qwStartTime.QuadPart) /
static_cast<double>(s_qwPerfFreq.QuadPart) :
0.0;
}
This can be used this way:
CMyTimer Timer(true);
_tprintf(_T("Code excution took %.5f seconds\n"), Timer.GetElapsedTime());