zoukankan      html  css  js  c++  java
  • C++ 如何得到当前进程所占用的内存呢?【转】

    使用SDK的PSAPI (Process Status Helper)
    中的
    BOOL
    GetProcessMemoryInfo(
    HANDLE Process,

    PPROCESS_MEMORY_COUNTERS ppsmemCounters,

    DWORD cb
    );

    typedef
    struct _PROCESS_MEMORY_COUNTERS {
    DWORD cb;
    DWORD PageFaultCount;

    SIZE_T PeakWorkingSetSize;
    //峰值内存使用
    SIZE_T WorkingSetSize;
    //内存使用
    SIZE_T QuotaPeakPagedPoolUsage;

    SIZE_T QuotaPagedPoolUsage;

    SIZE_T QuotaPeakNonPagedPoolUsage;

    SIZE_T QuotaNonPagedPoolUsage;

    SIZE_T PagefileUsage;
    //虚拟内存使用
    SIZE_T PeakPagefileUsage;
    //峰值虚拟内存使用
    } PROCESS_MEMORY_COUNTERS,
    *PPROCESS_MEMORY_COUNTERS;

    #include <iostream>
    #include <windows.h>
    #include <psapi.h>
    #pragma comment(lib,"psapi.lib")
    using namespace std;
    void showMemoryInfo(void)
    {
    HANDLE handle=GetCurrentProcess();
    PROCESS_MEMORY_COUNTERS pmc;
    GetProcessMemoryInfo(handle,&pmc,sizeof(pmc));
    cout<<"内存使用:"<<pmc.WorkingSetSize/1000 <<"K/"<<pmc.PeakWorkingSetSize/1000<<"K + "<<pmc.PagefileUsage/1000 <<"K/"<<pmc.PeakPagefileUsage/1000 <<"K"<<endl;
    }
    int main(int argc,char* argv)
    {
    showMemoryInfo();
    cout<<"回收所有可回收的内存"<<endl;
    EmptyWorkingSet(GetCurrentProcess());
    showMemoryInfo();
    cout<<"开始动态分配内存"<<endl;
    char* buf[5];
    for(int i=0;i<sizeof(buf)/sizeof(char*);i++)
    {
    buf[i]=new char[102400];
    showMemoryInfo();
    }
    cout<<"开始释放内存"<<endl;
    for(int i=0;i<sizeof(buf)/sizeof(char*);i++)
    {
    delete buf[i];
    buf[i]=NULL;
    showMemoryInfo();
    }
    cout<<"回收所有可回收的内存"<<endl;
    EmptyWorkingSet(GetCurrentProcess());
    showMemoryInfo();
    return 0;
    }

    输出:
    内存使用:1339K/1339K +
    356K/356K
    回收所有可回收的内存
    内存使用:114K/1425K +
    356K/356K
    开始动态分配内存
    内存使用:430K/1425K + 466K/466K
    内存使用:438K/1425K +
    573K/573K
    内存使用:446K/1425K + 679K/679K
    内存使用:454K/1425K +
    786K/786K
    内存使用:462K/1425K + 892K/892K
    开始释放内存
    内存使用:462K/1425K +
    794K/892K
    内存使用:454K/1425K + 692K/892K
    内存使用:446K/1425K +
    589K/892K
    内存使用:438K/1425K + 487K/892K
    内存使用:425K/1425K +
    360K/892K
    回收所有可回收的内存
    内存使用:110K/1425K + 360K/892K
  • 相关阅读:
    HTML基础-3
    HTML基础-2
    HTML基础-1
    hdu 1709 The Balance(母函数)
    hdu 2082 找单词(母函数)
    hdu 1085 Holding Bin-Laden Captive!(母函数)
    hdu 1028 Ignatius and the Princess III(母函数)
    hdu 1027 Ignatius and the Princess II(正、逆康托)
    康托展开、康托逆展开原理
    hdu 4288 Coder(单点操作,查询)
  • 原文地址:https://www.cnblogs.com/mazhenyu/p/5984743.html
Copyright © 2011-2022 走看看