Retrieving Runtime Memory Usage in C with /proc/pid
In C , obtaining information about a program's memory usage at runtime can be challenging. Despite attempts using getrusage(), the poster consistently encountered zero values. An alternative approach exists that involves querying files in the /proc/pid directory.
On Linux systems, /proc/pid contains process-specific information, including memory usage. One of the most reliable files for this purpose is /proc/self/stat. By parsing this file, we can extract the following fields:
To retrieve these values, we can utilize the process_mem_usage() function:
void process_mem_usage(double& vm_usage, double& resident_set) { // Parse /proc/self/stat ifstream stat_stream("/proc/self/stat"); stat_stream >> ... >> vsize >> rss; stat_stream.close(); // Convert to KB long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; vm_usage = vsize / 1024.0; resident_set = rss * page_size_kb; }
Within our main() function, we can use process_mem_usage() to print the virtual memory usage and resident set size:
int main() { double vm, rss; process_mem_usage(vm, rss); cout << "VM: " << vm << "; RSS: " << rss << endl; }
Using this approach, we can accurately obtain the memory usage information of the current program at runtime.
The above is the detailed content of How Can I Accurately Retrieve a C Program's Runtime Memory Usage on Linux?. For more information, please follow other related articles on the PHP Chinese website!