Home > Backend Development > C++ > How Can I Efficiently Monitor C Program Memory Usage (VIRT and RES) at Runtime?

How Can I Efficiently Monitor C Program Memory Usage (VIRT and RES) at Runtime?

Susan Sarandon
Release: 2024-12-05 21:22:10
Original
718 people have browsed it

How Can I Efficiently Monitor C   Program Memory Usage (VIRT and RES) at Runtime?

Using C to Get Memory Usage at Runtime

This article investigates how to obtain memory usage information, specifically VIRT and RES, at runtime in C .

Tried Approach and Challenges

An attempt to utilize the getrusage function for retrieving this data yielded consistently zero results.

Alternative Approach Using /proc Files

For Linux systems, reading data from "/proc/pid" files offers a reliable alternative to ioctl(). Here's a snippet with C constructs demonstrating this approach:

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

void process_mem_usage(double& vm_usage, double& resident_set)
{
    vm_usage = 0.0;
    resident_set = 0.0;

    ifstream stat_stream("/proc/self/stat", ios_base::in);
    
    string vsize, rss;
    stat_stream >> vsize >> rss;
    stat_stream.close();

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

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

The above is the detailed content of How Can I Efficiently Monitor C Program Memory Usage (VIRT and RES) at Runtime?. 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