Home >Backend Development >C++ >How Can I Efficiently Monitor C Program Memory Usage (VIRT and RES) at Runtime?
Using C to Get Memory Usage at Runtime
This article investigates how to obtain memory usage information, specifically VIRT and RES, at runtime in C .
Tried Approach and Challenges
An attempt to utilize the getrusage function for retrieving this data yielded consistently zero results.
Alternative Approach Using /proc Files
For Linux systems, reading data from "/proc/pid" files offers a reliable alternative to ioctl(). Here's a snippet with C constructs demonstrating this approach:
#include <unistd.h> #include <ios> #include <iostream> #include <fstream> #include <string> void process_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); string vsize, rss; stat_stream >> vsize >> rss; stat_stream.close(); long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; vm_usage = stod(vsize) / 1024.0; resident_set = stod(rss) * page_size_kb; } int main() { double vm, rss; process_mem_usage(vm, rss); std::cout << "VM: " << vm << "; RSS: " << rss << std::endl; }
The above is the detailed content of How Can I Efficiently Monitor C Program Memory Usage (VIRT and RES) at Runtime?. For more information, please follow other related articles on the PHP Chinese website!