#include <unistd.h>
#include <ios>
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <stdexcept>
#include <limits>
//
//
// process_mem_usage(double &, double &) - takes two doubles by reference,
// attempts to read the system-dependent data for a process' virtual memory
// size and resident set size, and return the results in KB.
//
// On failure, returns 0.0, 0.0
int GetRamInKB(void)
{
FILE* meminfo = fopen("/proc/meminfo", "r");
if (meminfo == NULL)
{
return -1;
}// handle error
char line[256];
while (fgets(line, sizeof(line), meminfo))
{
int ram;
if (sscanf(line, "MemTotal: %d kB", &ram) == 1)
{
fclose(meminfo);
return ram;
}
}
// If we got here, then we couldn't find the proper line in the meminfo file:
// do something appropriate like return an error code, throw an exception, etc.
fclose(meminfo);
return -1;
}
void new_big()
{
const size_t n=5*1024;
const size_t size=1024*1024;
char **array = new char*[n];
for (size_t a=0;a<n;a++){
array[a]=new char[size];
memset(array[a],0,size);
}
// for (size_t a=0;a<n;a++)
// delete[] array[a];
//delete[] array;
}
void process_mem_usage(double& vm_usage, double& resident_set)
{
using std::ios_base;
using std::ifstream;
using std::string;
vm_usage = 0.0;
resident_set = 0.0;
// 'file' stat seems to give the most reliable results
//
ifstream stat_stream("/proc/self/stat",ios_base::in);
// dummy vars for leading entries in stat that we don't care about
//
string pid, comm, state, ppid, pgrp, session, tty_nr;
string tpgid, flags, minflt, cminflt, majflt, cmajflt;
string utime, stime, cutime, cstime, priority, nice;
string O, itrealvalue, starttime;
// the two fields we want
//
unsigned long vsize;
long rss;
stat_stream >> pid >> comm >> state >> ppid >> pgrp >> session >> tty_nr
>> tpgid >> flags >> minflt >> cminflt >> majflt >> cmajflt
>> utime >> stime >> cutime >> cstime >> priority >> nice
>> O >> itrealvalue >> starttime >> vsize >> rss; // don't care about the rest
stat_stream.close();
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;
new_big();
unsigned long total = GetRamInKB();
while(1)
{
double vm, rss;
process_mem_usage(vm, rss);
cout << "VM: " << vm << "(KB); RSS: " << rss << endl;
printf("vm: %f\n",vm);
std::cout<<"total:"<< total<<"(KB)\n";
std::cout<<"memory usage:"<< 100*vm / total <<" %\n";
sleep(2);
}
}
g++ -o mem_usage mem_usage.cpp
结果:
VM: 5.27736e+06(KB); RSS: 5.26615e+06
vm: 5277356.000000
total:65752432(KB)
memory usage:8.0261 %