Skip to content

Instantly share code, notes, and snippets.

@thirdwing
Created August 16, 2014 19:57
Show Gist options
  • Save thirdwing/da4621eb163a886a03c5 to your computer and use it in GitHub Desktop.
Save thirdwing/da4621eb163a886a03c5 to your computer and use it in GitHub Desktop.
C++ code to print out runtime memory usage
#include <iostream>
#include <fstream>
#include <unistd.h>
void process_mem_usage(double& vm_usage, double& resident_set)
{
vm_usage = 0.0;
resident_set = 0.0;
// the two fields we want
unsigned long vsize;
long rss;
{
std::string ignore;
std::ifstream ifs("/proc/self/stat", std::ios_base::in);
ifs >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore
>> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore
>> ignore >> ignore >> vsize >> rss;
}
long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // in case x86-64 is configured to use 2MB pages
vm_usage = vsize / 1024.0;
resident_set = rss * page_size_kb;
}
int main()
{
using std::cout;
using std::endl;
double vm, rss;
process_mem_usage(vm, rss);
cout << "VM: " << vm << "; RSS: " << rss << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment