1

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!

Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
Sebastián
  • 11
  • 1
  • Is your compiler maybe optimising out the vector because it isn't being used? Try iterating the vector and pushing values into v. – Irelia Jul 31 '19 at 14:41
  • I understand that this allows you to get the resource usage up to a certain point, so in theory I could use the vector after that and this should take the vector into account. But yes, I tried writing values on the vector. Thanks for your comment anyways. – Sebastián Jul 31 '19 at 15:04
  • 1
    Have you tried modifying the 1024 to a larger value (e.g. 100,000)? perhaps 1024 is not enough to incur memory increase. – Tomer Jul 31 '19 at 15:13
  • Why wouldn't it be enough? In theory it's the number of KB, so a vector of 1024 ints should add 4KB. Anyways, I tried with 1024000 and the increase in the output didn't make any sense to me :/ Thanks for your comment. – Sebastián Aug 01 '19 at 17:44

1 Answers1

2

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

codeczar
  • 273
  • 1
  • 8
  • 22