MFC下获取系统内存和当前进程的内存使用情况
GlobalMemoryStatusEx来获取系统的内存使用情况
GetProcessMemoryInfo获取某个进程的内存使用情况。和任务管理器看到的是一样的。
具体代码如下:
void GetSystemMemoryInfo() { CString strInfo; MEMORYSTATUSEX statex; statex.dwLength = sizeof(statex); GlobalMemoryStatusEx(&statex); DWORDLONG physical_memory = statex.ullTotalPhys / (1024 * 1024); DWORDLONG avalid_memory = statex.ullAvailPhys / (1024 * 1024); DWORDLONG virtual_totalmemory = statex.ullTotalVirtual / (1024 * 1024); DWORDLONG virtual_memory = statex.ullAvailVirtual / (1024 * 1024); DWORDLONG usePhys = physical_memory - avalid_memory; DWORDLONG useVirtual = virtual_totalmemory - virtual_memory; float percent_memory = ((float)usePhys / (float)physical_memory) * 100; float percent_memory_virtual = ((float)useVirtual / (float)virtual_totalmemory) * 100; strInfo.Format("物理内存使用率:%.2f%% 物理内存:%lld MB 可用物理内存:%lld MB\n", percent_memory, physical_memory, avalid_memory); showText(strInfo); strInfo.Format("虚拟内存使用率:%.2f%% 虚拟内存:%lld MB 可用虚拟内存:%lld MB \n", percent_memory_virtual, virtual_totalmemory, virtual_memory); showText(strInfo); SYSTEM_INFO si; GetSystemInfo(&si); DWORD pid = GetCurrentProcessId(); HANDLE handle; handle = ::OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid); PROCESS_MEMORY_COUNTERS pmc; GetProcessMemoryInfo(handle, &pmc, sizeof(pmc)); int usedMemory = 0; PSAPI_WORKING_SET_INFORMATION workSet; memset(&workSet, 0, sizeof(workSet)); BOOL bOk = QueryWorkingSet(handle, &workSet, sizeof(workSet)); if (bOk || (!bOk && GetLastError() == ERROR_BAD_LENGTH)) { int nSize = sizeof(workSet.NumberOfEntries) + workSet.NumberOfEntries*sizeof(workSet.WorkingSetInfo); char* pBuf = new char[nSize]; if (pBuf) { QueryWorkingSet(handle, pBuf, nSize); PSAPI_WORKING_SET_BLOCK* pFirst = (PSAPI_WORKING_SET_BLOCK*)(pBuf + sizeof(workSet.NumberOfEntries)); DWORD dwMem = 0; for (ULONG_PTR nMemEntryCnt = 0; nMemEntryCnt < workSet.NumberOfEntries; nMemEntryCnt++, pFirst++) { if (pFirst->Shared == 0) { dwMem += si.dwPageSize; } } delete pBuf; pBuf = NULL; if (workSet.NumberOfEntries > 0) { usedMemory = dwMem / (1024 * 1024); } } } strInfo.Format("进程id:%d 已使用内存 %d MB\n", pid, usedMemory); showText(strInfo); CloseHandle(handle); }
需要引入头文件#include <psapi.h>
高山流水,海纳百川!