Skip to content

Instantly share code, notes, and snippets.

@kevinkreiser
Last active August 29, 2015 14:15
Show Gist options
  • Save kevinkreiser/53e1316c8d8be8201b24 to your computer and use it in GitHub Desktop.
Save kevinkreiser/53e1316c8d8be8201b24 to your computer and use it in GitHub Desktop.
Programmatically Get at Memory Usage via Proc Status
#include <fstream>
#include <string>
#include <iostream>
#include <cinttypes>
#include <utility>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#include <list>
struct memory_status {
memory_status(const std::unordered_set<std::string> interest = {}){
//grab the vm stats from the file
std::ifstream file("/proc/self/status");
std::string line;
while(std::getline(file, line)){
//did we find a memory metric
if(line.find_first_of("Vm") == 0){
//grab the name of it and see if we care about it
std::string name = line.substr(0, line.find_first_of(':'));
if(interest.size() > 0 && interest.find(name) == interest.end())
continue;
//try to get the number of bytes
std::remove_if(line.begin(), line.end(), [](const char c) {return !std::isdigit(c);});
if(line.size() == 0)
continue;
auto bytes = std::stod(line) * 1024.0;
//get the units and scale
std::pair<double, std::string> metric = std::make_pair(bytes, "b");
for(auto unit : { "B", "KB", "MB", "GB" }){
metric.second = unit;
if (metric.first > 1024.0)
metric.first /= 1024.0;
else
break;
}
metrics.emplace(std::piecewise_construct, std::forward_as_tuple(name), std::forward_as_tuple(metric));
}
line.clear();
}
}
std::unordered_map<std::string, std::pair<double, std::string> > metrics;
friend std::ostream& operator<<(std::ostream&, const memory_status&);
};
std::ostream& operator<<(std::ostream& stream, const memory_status& s){
for(const auto& metric : s.metrics)
stream << metric.first << ": " << metric.second.first << metric.second.second << std::endl;
return stream;
}
int main(){
std::list<uint32_t> ints;
for(uint32_t i = 0; i < std::numeric_limits<uint32_t>::max() / 100; ++i)
ints.push_back(i);
std::cout << memory_status({"VmSize", "VmPeak", "VmRss", "VmSwap"});
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment