linux和windows获取RAM全局瞬时占用

2023-12-28 03:18:31

?linux

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

class SystemMonitor {
public:
    long getMemoryUsage() const {
        std::ifstream meminfoFile("/proc/meminfo");
        if (!meminfoFile.is_open()) {
            std::cerr << "Failed to open /proc/meminfo file.\n";
            return -1;
        }

        std::string line;
        long totalMemory = -1;
        long freeMemory = -1;

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

            if (iss >> key >> value) {
                if (key == "MemTotal:") {
                    totalMemory = value;
                } else if (key == "MemFree:") {
                    freeMemory = value;
                    break;  // No need to continue after finding MemFree
                }
            }
        }

        if (totalMemory == -1 || freeMemory == -1) {
            std::cerr << "Failed to extract memory information from /proc/meminfo.\n";
            return -1;
        }

        // Calculate used memory
        long usedMemory = totalMemory - freeMemory;

        return usedMemory / 1024;
    }
};

int main() {
    SystemMonitor monitor;

    // Example: Print used memory every 1 second
    for (int i = 0; i < 5; ++i) {
        sleep(1);
        std::cout << "Used Memory: " << monitor.getMemoryUsage() << " MB\n";
    }

    return 0;
}

windows

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

class SystemMonitor {
public:
    long getMemoryUsage() const {
        MEMORYSTATUSEX memoryStatus;
        memoryStatus.dwLength = sizeof(memoryStatus);

        if (GlobalMemoryStatusEx(&memoryStatus)) {
            // 获取已用内存大小(物理内存 + 页面文件)
            long usedMemory = static_cast<long>(memoryStatus.ullTotalPhys - memoryStatus.ullAvailPhys +
                                               memoryStatus.ullTotalPageFile - memoryStatus.ullAvailPageFile);
            return usedMemory / (1024 * 1024);  // 转换为 MB
        } else {
            std::cerr << "Failed to get memory information.\n";
            return -1;
        }
    }
};

int main() {
    SystemMonitor monitor;

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

    return 0;
}

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