getrusage 没有像我预期的那样工作

getrusage not working as I would expect

我正在尝试使用以下代码通过 getrusage 系统调用测量子进程使用的内存量

#include <iostream>
using std::cout;
using std::endl;
#include <unistd.h>
#include <thread>
#include <chrono>
#include <sys/wait.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <cassert>
#include <vector>

int main() {

    auto child_pid = fork();
    if (!child_pid) {
        cout << "In child process with process id " << getpid() << endl;
        cout << "Child's parent process is " << getppid() << endl;
        std::this_thread::sleep_for(std::chrono::seconds(2));

        std::vector<int> vec;
        vec.resize(10000);
        for (auto ele : vec) {
            cout << ele << endl;
        }

    } else {
        // this will wait for the child above to finish
        waitpid(child_pid, nullptr, 0);
        struct rusage usage;
        int return_val_getrusage = getrusage(RUSAGE_CHILDREN, &usage);
        assert(!return_val_getrusage);
        cout << "Memory used by child " << usage.ru_maxrss << endl;
    }

    return 0;
}

我通过在 vector::resize() 调用中输入不同的参数来不断更改分配的内存量。然而,这总是打印一个大约 2300 的值用于子内存使用。我不确定这是测量子进程内存使用情况的正确方法。即使我在分配向量之前在子进程中使用 RUSAGE_SELF 添加对 getrusage 的调用,ru_maxrss 的值保持不变。谁能告诉我在这里我可以做得更好吗?

堆和自由存储的内部管理是实现定义的,取决于底层操作系统。

通常出于性能原因,并非每次分配都会导致 os 请求更多 space:标准库将汇集一些进程内存,并且仅当没有足够大小的块时才扩展池找到了。

因此,我支持ose,您尝试过的各种大小仍在开始时分配的几 MB 之内。您应该尝试非常大的分配以找到差异。