获取当前进程RAM瞬时占用[windows][linux][c++]

发布时间:2023年12月28日

?windows

#include <iostream>
#include <windows.h>

class ProcessMemoryMonitor {
public:
    long getProcessMemoryUsage() const {
        PROCESS_MEMORY_COUNTERS_EX pmc;
        if (GetProcessMemoryInfo(GetCurrentProcess(), reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&pmc), sizeof(pmc))) {
            // 获取已用物理内存大小
            long usedMemory = static_cast<long>(pmc.WorkingSetSize);
            return usedMemory / (1024 * 1024);  // 转换为 MB
        } else {
            std::cerr << "Failed to get process memory information.\n";
            return -1;
        }
    }
};

int main() {
    ProcessMemoryMonitor monitor;

    // Example: Print used memory every 1 second
    for (int i = 0; i < 5; ++i) {
        Sleep(1000);
        std::cout << "Process Memory Usage: " << monitor.getProcessMemoryUsage() << " MB\n";
    }

    return 0;
}

linux

#include <iostream>
#include <fstream>
#include <sstream>
#include <unistd.h>

class ProcessMemoryMonitor {
public:
    long getProcessMemoryUsage() const {
        std::ifstream statusFile("/proc/self/status");
        if (!statusFile.is_open()) {
            std::cerr << "Failed to open /proc/self/status file.\n";
            return -1;
        }

        std::string line;
        long vmRSS = -1;

        // Read the file line by line
        while (std::getline(statusFile, line)) {
            std::istringstream iss(line);
            std::string key;
            long value;

            if (iss >> key >> value) {
                if (key == "VmRSS:") {
                    vmRSS = value;
                    break;  // No need to continue after finding VmRSS
                }
            }
        }

        if (vmRSS == -1) {
            std::cerr << "Failed to extract VmRSS information from /proc/self/status.\n";
            return -1;
        }

        // VmRSS is in kilobytes, converting to megabytes
        return vmRSS / 1024;
    }
};

int main() {
    ProcessMemoryMonitor monitor;

    // Example: Print process memory usage every 1 second
    for (int i = 0; i < 5; ++i) {
        sleep(1);
        std::cout << "Process Memory Usage: " << monitor.getProcessMemoryUsage() << " MB\n";
    }

    return 0;
}

?

文章来源:https://blog.csdn.net/wo871427008/article/details/135258041
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。