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