Home >Backend Development >C++ >How Can I Accurately Monitor C Memory Usage at Runtime?
Obtaining accurate memory usage metrics at runtime is crucial for optimizing performance and debugging memory-related issues. This article explores different approaches to retrieve memory usage information in C applications, primarily focusing on the virtual memory size (VIRT) and resident set size (RES).
The initial attempt to employ the getrusage() function often results in obtaining zero values, as demonstrated in the provided code snippet. This is primarily because getrusage() retrieves resource usage information from the entire system rather than the specific process.
On Linux systems, a more reliable approach involves reading information from the /proc/pid directory. Each process has its own dedicated directory where various statistics are maintained.
The following code snippet provides a utility function (process_mem_usage()) that reads the /proc/self/stat file to obtain the process's virtual memory size (vsize) and resident set size (rss):
void process_mem_usage(double& vm_usage, double& resident_set) { ifstream stat_stream("/proc/self/stat", ios_base::in); unsigned long vsize; long rss; stat_stream >> vsize >> rss; long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; vm_usage = vsize / 1024.0; resident_set = rss * page_size_kb; }
The main function calls process_mem_usage() to retrieve the memory usage information and prints it to the console:
int main() { double vm, rss; process_mem_usage(vm, rss); cout << "VM: " << vm << "; RSS: " << rss << endl; }
The above is the detailed content of How Can I Accurately Monitor C Memory Usage at Runtime?. For more information, please follow other related articles on the PHP Chinese website!