Is getrusage not working for me? Why?

684 views Asked by At

I'm trying to measure the maximum resident set size and I found that you can do so with getrusage:

When I run this

#include <iostream>
#include<vector>
#include <sys/resource.h>

using namespace std;

int main(int argc, char* argv[]){

    int who = RUSAGE_SELF;
    struct rusage usage;
    int ret = -1;

    vector<int> v(1024);

    ret = getrusage(who, &usage);
    if (ret == 0) cout << usage.ru_maxrss << endl;

    return 0;
}

I get the same value as I do when I comment the declaration of the vector.

Is there anything I'm doing wrong?

Thanks!

1

There are 1 answers

0
codeczar On

I have modified your code a bit to make sense for you for the data which is shown by the ru_maxrss element of rusage structure.

Here is my code

#include <vector>
#include <sys/resource.h>

using namespace std;

int main(int argc, char* argv[]){

    int who = RUSAGE_SELF;
    struct rusage usage;
    int ret = -1;
    long int a,b;

getrusage(who, &usage);
a=usage.ru_maxrss;

cout << "Maximum resident set size before vector allocation   "<<a << endl;
    vector<int> v(10240000);

cout<<"Size of vector v in kilobytes (kB)  "<<(v.size()*sizeof(int))/(1024)<<endl;

    ret = getrusage(who, &usage);

    cout<<"Size of integer data type   "<<sizeof(int)<<endl;
    b=usage.ru_maxrss;

    if (ret == 0) 
cout << "Maximum resident set size after vector allocation  "<<b << endl;
 cout<<"Difference between resident set size before and after vector allocation  "<<b-a<<endl;

    return 0;
}

Each time getrusage() is called it allocates a different resident set size which is a few kB(approx 600-800) greater than the size allocated for the vector.

Some of the outputs of the above code are as follow enter image description here

enter image description here

If I reduce the no. of elements in the vector to 1024000 the output is as follow enter image description here