Home > Backend Development > C++ > How Can I Accurately Retrieve a C Program's Runtime Memory Usage on Linux?

How Can I Accurately Retrieve a C Program's Runtime Memory Usage on Linux?

Mary-Kate Olsen
Release: 2024-12-11 09:34:14
Original
205 people have browsed it

How Can I Accurately Retrieve a C   Program's Runtime Memory Usage on Linux?

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:

  • vsize: Program's virtual memory size in kilobytes (KB)
  • rss: Program's resident set size in KB (amount of physical memory currently being used)

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;
}
Copy after login

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template