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

时间:2016-03-05 07:59:34

标签: c++ linux c++11 c++14 waitpid

我正在尝试使用以下代码通过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左右打印一个值,以供孩子使用。我不确定这是测量子进程的内存使用情况的正确方法。即使我在分配向量之前在子进程中添加getrusage RUSAGE_SELF的调用,ru_maxrss的值仍然相同。有人可以告诉我在这里可以做得更好吗?

1 个答案:

答案 0 :(得分:3)

heap和freestore的内部管理是实现定义的,取决于底层操作系统。

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

因此,我认为您尝试过的变量大小仍然在开始时分配的几个MB范围内。你应该尝试非常大的分配来找到差异。

相关问题