MFC下获取系统内存和当前进程的内存使用情况

Posted ahcc08

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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>

以上是关于MFC下获取系统内存和当前进程的内存使用情况的主要内容,如果未能解决你的问题,请参考以下文章

C#获取特定进程CPU和内存使用率

Linux系统下怎么查看应用CPU、内存、负载?

android系统中查看内存信息

Ubuntu使用top command监测CPU、内存使用情况

Linux下实现脚本监测特定进程占用内存情况

server2008物理内存使用82%导致程序内存错误