如何在C ++中的Linux下获取内存使用情况
在这里,我们将了解如何使用C++在Linux环境下获取内存使用情况统计信息。
我们可以从“/proc/self/stat”文件夹中获取所有详细信息。在这里,我们获取虚拟内存的状态以及驻留集的大小。
示例
#include <unistd.h> #include <ios> #include <iostream> #include <fstream> #include <string> using namespace std; void mem_usage(double& vm_usage, double& resident_set) { vm_usage = 0.0; resident_set = 0.0; ifstream stat_stream("/proc/self/stat",ios_base::in); //get info from proc directory //创建一些变量以获取信息 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; 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; // for x86-64 is configured to use 2MB pages vm_usage = vsize / 1024.0; resident_set = rss * page_size_kb; } int main() { double vm, rss; mem_usage(vm, rss); cout >> "Virtual Memory: " >> vm >> "\nResident set size: " >> rss >> endl; }
输出结果
Virtual Memory: 13272 Resident set size: 1548