Search code examples
c++linuxc++11c++14waitpid

getrusage not working as I would expect


I am trying to measure the amount of memory used by a child process via the getrusage system call with the following code

#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;
}

I keep changing the amount of memory I am allocating by putting in different arguments to the vector::resize() call. This however always prints a value around 2300 for memory usage by child. I am not sure this is the right way to go about measuring memory usage for a child process. Even if I add calls to getrusage with RUSAGE_SELF in the child process before the allocation of the vector, the value of ru_maxrss remains the same. Could someone tell me what I can do better here?


Solution

  • The internal management of heap and freestore are implementation defined and depend on underlying operating system.

    Usually for performance reasons not every allocation will result in more space requested from os: the standard library will pool some process memory and will extend the pool only if no block of sufficient size is found.

    I therefore suppose that the varrying sizes you've tried are still within the couple of MBs allocated at start. You should try really big allocations to find a difference.