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

 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;
}

 

  • 11
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值