Home >Backend Development >C++ >How Can I Monitor a C Program's Memory Usage in Linux?

How Can I Monitor a C Program's Memory Usage in Linux?

Barbara Streisand
Barbara StreisandOriginal
2024-12-20 02:28:13731browse

How Can I Monitor a C   Program's Memory Usage in Linux?

How to Monitor Memory Usage of a Running Program in C

Estimating memory consumption during runtime is crucial for optimizing application performance and preventing memory leaks. C provides multiple approaches to retrieve memory usage information, addressing specific requirements.

One method frequently employed is leveraging the getrusage function, which retrieves data about a process's resource utilization. However, in certain cases, users encounter difficulties obtaining accurate results using this approach.

Alternative Solution for Linux Environments

For Linux systems, an alternative strategy involves accessing files within the /proc/pid directory. Each file presents varying information related to system processes. The following code snippet illustrates how to obtain both virtual memory size (VM) and resident set size (RSS) in Kilobytes (KB):

#include <unistd.h>
#include <ios>
#include <iostream>
#include <fstream>
#include <string>

void process_mem_usage(double& vm_usage, double& resident_set) {
    std::ifstream stat_stream("/proc/self/stat", std::ios_base::in);

    unsigned long vsize;
    long rss;

    stat_stream >> vsize >> rss; // Skipping irrelevant fields

    long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024;
    vm_usage = vsize / 1024.0;
    resident_set = rss * page_size_kb;
}

Usage Example

To utilize this method, integrate the process_mem_usage function into your program and call it to retrieve current memory usage:

int main() {
    double vm, rss;
    process_mem_usage(vm, rss);
    std::cout << "VM: " << vm << "; RSS: " << rss << std::endl;
}

This approach provides reliable estimates of memory usage, supplementing the limitations encountered with other methods.

The above is the detailed content of How Can I Monitor a C Program's Memory Usage in Linux?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn