C++ Performance measuring utility classes

less than 1 minute read

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#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