這段代碼實現在類構造函數中獲取進程內存的使用,在析構時打印出進程內存使用的改變量。
class CAutoMem
{
public:
CAutoMem(char* vInfo):strMem(vInfo){
Init();
}
~CAutoMem(){
PrintMem();
}
void Init()
{
dwPrcID = GetCurrentProcess();
PROCESS_MEMORY_COUNTERS pmc;
GetProcessMemoryInfo((HANDLE)dwPrcID, &pmc, sizeof(pmc));
dwMemSize = pmc.WorkingSetSize;
}
void PrintMem()
{
PROCESS_MEMORY_COUNTERS pmc;
GetProcessMemoryInfo((HANDLE)dwPrcID, &pmc, sizeof(pmc));
if(pmc.WorkingSetSize > dwMemSize)
{
if(pmc.WorkingSetSize - dwMemSize > 1024)
{
printf("%s內存申請 %d\n\n", strMem.c_str(), (pmc.WorkingSetSize - dwMemSize)/1024);
}
}
else
{
if(pmc.WorkingSetSize - dwMemSize > 1024)
{
printf("%s內存釋放 %d\n\n", strMem.c_str(), (dwMemSize - pmc.WorkingSetSize)/1024);
}
}
}
public:
string strMem;
HANDLE dwPrcID;
DWORD dwMemSize;
};
本文出自 “阿木雪” 博客,謝絕轉載!