linux中查看C/C++程序或调用其中某个函数(类)消耗内存的方法实现

验证C/C++程序或调用其中某个函数(类)消耗内存的方法:

获取进程ID,调用/proc/[pid]/status查看消耗的内存页(4KB/内存页)

进程ID获取方法

UNIX环境高级编程中提到的getpid(),可以获取。 头文件<unistd.h>

查看内存信息

sprintf(FILE_NAME, "/proc/%d/statm", pid);
FILE *fp = fopen(FILE_NAME, "r");
fscanf(fp, "%lu %lu %lu %lu %lu %lu %lu", &result.size, &result.resident, &result.share, &result.text, &result.lib, &result.data, &result.dt);

附:代码

代码来自参考1,已验证可用

在需要查看的地方调用void showMemStat(pid_t pid)即可。

#include <unistd.h>

#define FILE_NAME_SIZE 255

typedef struct {
    unsigned long size, resident, share, text, lib, data, dt;
}statm_t;

statm_t get_statm(pid_t pid);

void showMemStat(pid_t pid);
void displayStatm(pid_t pid, statm_t statm);
statm_t get_statm(pid_t pid)
{
    statm_t result = {0,0,0,0,0,0,0};

    char FILE_NAME[FILE_NAME_SIZE] = "/proc/self/statm";
    sprintf(FILE_NAME, "/proc/%d/statm", pid);

    FILE *fp = fopen(FILE_NAME, "r");
    fscanf(fp, "%lu %lu %lu %lu %lu %lu %lu", &result.size, &result.resident, &result.share, &result.text, &result.lib, &result.data, &result.dt);
    fclose(fp);
    return result;
}

void displayStatm(pid_t pid, statm_t statm)
{
    printf("Process %d Memory Use:\n", pid);
    printf("\t size \t resident \t share \t text \t lib \t data \t dt \n");
    printf("==========================================================\n");
    printf("\t %lu \t %lu \t\t %lu \t %lu \t %lu \t %lu \t %lu \n", statm.size, statm.resident, statm.share, statm.text, statm.lib, statm.data, statm.dt);
}

void showMemStat(pid_t pid)
{
    statm_t statm = get_statm(pid);
    displayStatm(pid, statm);
}

参考

  1. 编写Linux C程序,程序在运行时,如何知道自身占用内存情况,就像top按PID所得的那样? - 静静的回答 - 知乎
    https://www.zhihu.com/question/63504162/answer/209953202
  2. 查看进程所占内存/proc/[pid]/statm踩坑记 https://blog.csdn.net/dutsoft/article/details/51250374

猜你喜欢

转载自blog.csdn.net/dreamstone_xiaoqw/article/details/80402919