GetProcessMemoryInfo

本文通过C++示例代码展示了如何获取当前进程的内存使用情况,包括工作集大小及其峰值,页面文件使用情况等,并演示了动态分配和释放内存的过程及对内存使用的影响。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

GetProcessMemoryInfo

#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/1024 <<"/"<<pmc.PeakWorkingSetSize/1024<<" + "<<pmc.PagefileUsage/1024 <<"/"<<pmc.PeakPagefileUsage/1024 <<""<<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;
}





#include <stdio.h>
#include <windows.h>
#include <TlHelp32.h>

int main(int argc,char **argv)
{
    HANDLE handle;
    handle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
    if(handle == INVALID_HANDLE_VALUE)
    {
        printf("Gain snapshot falid\n");
        return -1;
    }

    PROCESSENTRY32 pe;
    pe.dwSize = sizeof(pe);
    BOOL flag = Process32First(handle,&pe);
    while(flag){
        char buff[MAX_PATH];
        sprintf(buff,"%i---------%s",pe.th32ProcessID,pe.szExeFile);
        printf("%s\n",buff);
        flag = Process32Next(handle,&pe);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值