C++ Performance measuring utility classes

#ifdef _DEBUG
#define ENABLED_MEASURE_PERFORMANCE
#endif
#define ENABLED_MEASURE_PERFORMANCE

#ifdef ENABLED_MEASURE_PERFORMANCE
class MeasureTime
{
public:
	MeasureTime()
	{
		memset(&m_startTick, 0, sizeof(m_startTick));
	}
 
	~MeasureTime()
	{
	}
 
	void Start(std::wstring const& name)
	{
		wchar_t strFormat[512];

		swprintf_s(strFormat, 512, L"[MEASURE TIME - BEGIN] %s\n", name.c_str());
		OutputDebugString(strFormat);

		m_name = name;
		QueryPerformanceFrequency(&m_startTick);
		m_frequency = ((double)m_startTick.QuadPart) / 1000.0;
		QueryPerformanceCounter(&m_startTick);
	}
 
	void Stop()
	{
		LARGE_INTEGER curTick;
		QueryPerformanceCounter(&curTick);

		auto delay = curTick.QuadPart - m_startTick.QuadPart;
		auto elapsed = (double)delay / m_frequency;
		wchar_t strFormat[512];

		swprintf_s(strFormat, 512, L"[MEASURE TIME - END  ] %s - %lf(ms)\n", m_name.c_str(), elapsed);
		OutputDebugString(strFormat);
	}
 
private:
	LARGE_INTEGER m_startTick;
	double m_frequency;
	std::wstring m_name;
};
 
class MeasureTimeScope
{
public:
	MeasureTimeScope(std::wstring const& name)
	{
		m_measure.Start(name);
	}
 
	MeasureTimeScope(wchar_t const* name)
	{
		m_measure.Start(name);
	}
 
	~MeasureTimeScope()
	{
		m_measure.Stop();
	}
 
private:
	MeasureTime m_measure;
};

#define MEASURE_TIME_SCOPE(X) MeasureTimeScope measure(L#X)
#else
#define MEASURE_TIME_SCOPE(X)
#endif

Advertisements
This entry was posted in C++, Performance, Programming. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s