How to Obtain Memory Usage Information at Runtime Using C
Introduction
Monitoring memory usage is crucial for optimizing program performance and preventing memory leaks. In C , obtaining real-time information about memory consumption can be essential for various debugging and optimization purposes.
Problem Statement
The OP attempted to utilize getrusage() to retrieve memory usage statistics (VIRT and RES) during program execution but consistently encountered zero values.
Solution
On Linux systems, retrieving memory usage via ioctl() can be challenging. Instead, a more reliable approach is to access information from files within /proc/pid. The following C code snippet demonstrates how to implement this approach:
#include <unistd.h> #include <ios> #include <iostream> #include <fstream> #include <string> void process_mem_usage(double& vm_usage, double& resident_set) { using namespace std; ifstream stat_stream("/proc/self/stat", ios_base::in); // Ignore irrelevant fields string pid, comm, state, ppid, pgrp, session, tty_nr, tpgid, flags, minflt, cminflt, majflt, cmajflt; string utime, stime, cutime, cstime, priority, nice, O, itrealvalue, starttime; // Read desired fields 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; // Ignore rest stat_stream.close(); // Convert values to KB long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; vm_usage = vsize / 1024.0; resident_set = rss * page_size_kb; }
Usage Example
To utilize the process_mem_usage() function for displaying memory usage information, you can write a simple main function as follows:
int main() { using std::cout; using std::endl; double vm, rss; process_mem_usage(vm, rss); cout << "VM: " << vm << "; RSS: " << rss << endl; }
By running this code during program execution, you can obtain the virtual memory usage (VM) and resident set size (RSS) at runtime.
The above is the detailed content of How to Reliably Get C Runtime Memory Usage on Linux?. For more information, please follow other related articles on the PHP Chinese website!