Trên Linux, thông tin bộ nhớ của tiến trình hiện tại có sẵn trong file ảo /proc/self/status hoặc /proc/self/stat. Chương trình dưới đây đọc /proc/self/stat để lấy Virtual Memory Size (VMS) và Resident Set Size (RSS).
Giải thích các chỉ số
- VMS (Virtual Memory Size): Tổng bộ nhớ ảo đã cấp phát (kể cả không dùng)
- RSS (Resident Set Size): Bộ nhớ vật lý thực tế đang sử dụng (RAM)
Mã nguồn hoàn chỉnh
#include <unistd.h>
#include <ios>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void get_memory_usage(double& vm_usage, double& resident_set) {
vm_usage = 0.0;
resident_set = 0.0;
// Mở /proc/self/stat
ifstream stat_stream("/proc/self/stat", ios_base::in);
if (!stat_stream) {
cerr << "Khong the mo /proc/self/stat" << endl;
return;
}
// Các trường trong /proc/self/stat (man proc để xem chi tiết)
string pid, comm, state, ppid, pgrp, session, tty_nr;
string tpgid, flags, minflt, cminflt, majflt, cmajflt;
string utime, stime, cutime, cstime, priority, nice;
string O, itrealvalue, starttime;
unsigned long vsize; // Virtual memory size (bytes)
long rss; // Resident Set Size (pages)
// Đọc theo thứ tự các trường
stat_stream >> pid >> comm >> state >> ppid >> pgrp >> session >> tty_nr
>> tpgid >> flags >> minflt >> cminflt >> majflt >> cmajflt
>> utime >> stime >> cutime >> cstime >> priority >> nice
>> O >> itrealvalue >> starttime >> vsize >> rss;
stat_stream.close();
// Kích thước trang (page size) - thường 4KB trên x86-64
long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024;
// Chuyển đổi đơn vị
vm_usage = vsize / 1024.0; // KB
resident_set = rss * page_size_kb; // KB
}
int main() {
double vm, rss;
get_memory_usage(vm, rss);
cout << "Virtual Memory (VMS): " << vm << " KB" << endl;
cout << "Resident Set Size (RSS): " << rss << " KB" << endl;
// Hiển thị thêm dưới MB
cout << "VMS: " << (vm / 1024.0) << " MB" << endl;
cout << "RSS: " << (rss / 1024.0) << " MB" << endl;
}
Kết quả mẫu
Virtual Memory (VMS): 13272 KB Resident Set Size (RSS): 1548 KB VMS: 12.96 MB RSS: 1.51 MB
Phương pháp thay thế: Đọc /proc/self/status
Dễ đọc hơn, dùng định dạng key-value:
void get_memory_usage_v2(double& vm, double& rss) {
ifstream status("/proc/self/status");
string line;
while (getline(status, line)) {
if (line.rfind("VmSize:", 0) == 0) {
vm = stod(line.substr(7)) / 1024.0; // VmSize trong KB
} else if (line.rfind("VmRSS:", 0) == 0) {
rss = stod(line.substr(6)) / 1024.0; // VmRSS trong KB
}
}
}
Lưu ý
- Chỉ hoạt động trên Linux (không dùng được trên Windows/macOS)
- Cần quyền đọc /proc (thường có mặc định)
- Cross-platform: Dùng
boost::processhoặcGetProcessMemoryInfo(Windows)