码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2019-08-10 11:50:09      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:info   open   ota   nbsp   ems   api   文件   cstring   virt   

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下获取系统内存和当前进程的内存使用情况

标签:info   open   ota   nbsp   ems   api   文件   cstring   virt   

原文地址:https://www.cnblogs.com/ahcc08/p/11330779.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!