6

在 C++ 中实时获取程序占用的内存量

 3 years ago
source link: https://zhiqiang.org/coding/get-pysical-memory-used-by-process-in-cpp.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

在 C++ 中实时获取程序占用的内存量

作者: 张志强

, 发表于 2019-02-09

, 共 903 字 , 共阅读 1313 次

获取程序占用的内存量,是一个诡异的需求。但程序写多了,有时候还真需要,尤其是代码运行出现问题的时候。

1. 实现代码

下面代码在 ubuntu 18.04 下通过。代码仅依赖 Linux 的内核功能,理论上适用于大部分 Linux 发行版。

// 实时获取程序占用的内存,单位:kb。
size_t physical_memory_used_by_process()
{
    FILE* file = fopen("/proc/self/status", "r");
    int result = -1;
    char line[128];

    while (fgets(line, 128, file) != nullptr) {
        if (strncmp(line, "VmRSS:", 6) == 0) {
            int len = strlen(line);

            const char* p = line;
            for (; std::isdigit(*p) == false; ++p) {}

            line[len - 3] = 0;
            result = atoi(p);

            break;
        }
    }

    fclose(file);

    return result;
}

注意,该程序读取的是程序占用的物理内存,也就是系统实际在物理内存上分配给程序的内存。程序申请,但没有读写过的地址空间,不一定对应了物理内存(操作系统很聪明)。长时间不用的内存,也可以被移出物理内存,移入虚拟内存。

代码很简单,它依赖了 Linux 的/proc/self/status文件。这个并不是一个真实存在的文件,而为 Linux 的一个内核接口。它里面提供了当前线程的很多信息,包括了内存占用量,具体可参考Linux Programmer's Manual

Q. E. D.

avatar-0.jpg

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK