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