这个能分析代码块执行消耗时间和消耗的内存
#ifndef MYPROFILER_H_
#define MYPROFILER_H_
#include <Windows.h>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <psapi.h>
#pragma comment(lib,"psapi.lib")
class MyProfiler
{
public:
MyProfiler(std::string str)
{
m_traceStr = str;
ZeroMemory(&m_QPFrequency, sizeof(m_QPFrequency));
ZeroMemory(&m_ElapsedTime, sizeof(m_ElapsedTime));
ZeroMemory(&m_StartCounter,sizeof(m_StartCounter));
m_Retval = 0;
// Query Frecuency
m_Retval = QueryPerformanceFrequency(&m_QPFrequency);
m_Retval = QueryPerformanceCounter (&m_StartCounter);
m_StartMemKB = GetMaxMemkb();
}
~MyProfiler()
{
m_Retval = QueryPerformanceCounter (&m_EndCounter);
m_ElapsedTime = (m_EndCounter.QuadPart - m_StartCounter.QuadPart );
long curMemKB = GetMaxMemkb();
long addMemKB = curMemKB - m_StartMemKB;
std::stringstream stream;
stream <<m_traceStr << " " << "ticks:" << m_ElapsedTime << " seconds:" << SecsFromTicks(m_ElapsedTime);
if ( abs(addMemKB) < 1024 )
{
stream << " mem:" << addMemKB << " kb";
}
else if ( abs(addMemKB) < 1024 * 1024 )
{
stream << " mem:" << addMemKB / 1024.0f << " mb";
}
stream << "\n";
OutputDebugString(stream.str().c_str());
}
protected:
double SecsFromTicks (__int64 ticks)
{
return static_cast<double>(ticks) / static_cast<double>(m_QPFrequency.QuadPart);
}
long GetMaxMemkb()
{
PROCESS_MEMORY_COUNTERS pmc ;
GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc));
return pmc.PeakWorkingSetSize/1024;
}
private:
LARGE_INTEGER m_QPFrequency; // ticks/sec resolution
LARGE_INTEGER m_StartCounter; // start time
LARGE_INTEGER m_EndCounter; // finish time
__int64 m_ElapsedTime; // elapsed time
DWORD m_Retval; // return value for API functions
std::string m_traceStr;
long m_StartMemKB;
};
#define MYPROFILER(X) MyProfiler _profiler(X)
#endif