// Stopwatch.cpp: implementation of the CStopwatch class. // ///////////////////////////////////////////////////////////////////// #include "Stopwatch.h" #include "Timers_i.c" #include // Multimedia timers ///////////////////////////////////////////////////////////////////// // Construction/Destruction ///////////////////////////////////////////////////////////////////// CStopwatch::CStopwatch() { // Initialize the member variables m_nStartTime.QuadPart = 0; m_nReferenceCount = 0; // Save the frequency of the performance counters QueryPerformanceFrequency ((LARGE_INTEGER*) &m_nFrequency); } CStopwatch::~CStopwatch() { } ///////////////////////////////////////////////////////////////////// // IUnknown Functions ///////////////////////////////////////////////////////////////////// HRESULT __stdcall CStopwatch::QueryInterface( REFIID riid, void **ppvObject) { HRESULT hr = S_OK; if (riid == IID_IUnknown) *ppvObject = static_cast( static_cast(this)); else if (riid == IID_IStopwatch) *ppvObject = static_cast(this); else { ppvObject = NULL; hr = E_NOINTERFACE; } if (SUCCEEDED(hr)) (static_cast(*ppvObject))->AddRef(); return hr; } unsigned long __stdcall CStopwatch::AddRef() { return InterlockedIncrement( &m_nReferenceCount ); } unsigned long __stdcall CStopwatch::Release() { if (InterlockedDecrement( &m_nReferenceCount ) == 0) { delete this; return 0; } return m_nReferenceCount; } ///////////////////////////////////////////////////////////////////// // Stopwatch Function Implementation ///////////////////////////////////////////////////////////////////// HRESULT __stdcall CStopwatch::Start() { if ( QueryPerformanceCounter( (LARGE_INTEGER*) &m_nStartTime) ) return S_OK; else return E_FAIL; } HRESULT __stdcall CStopwatch::ElapsedTime(float *Time) { HRESULT hr; LARGE_INTEGER nStopTime; // Set the stop time immediately so that a minimum // amount of timer code is executed between the start // and stop times if ( !QueryPerformanceCounter( (LARGE_INTEGER*) &nStopTime ) || (m_nStartTime.QuadPart == 0) ) { // Either QPC failed or // start was not called before stop hr = E_FAIL; } else { *Time = (float) (nStopTime.QuadPart - m_nStartTime.QuadPart); *Time = (*Time / m_nFrequency.QuadPart); hr = S_OK; } return hr; }