有时候程序会出现内存OOM的情况,这时并不会有相应的log输出,不容易定位到问题所在。最好能够在程序中监控内存,但目前没有很好的方法,Linux下可以使用top命令来查看,如:
top -n 2 -d 1 —p [PID] -b > top.log -n 刷新次数 -d 刷新时间 -p 指定进程 -b 批处理,不是原地刷新
但是这样得在跑程序的时候盯着看,很麻烦很累。。。
所以整理了几个C++和python的内存监测程序的实现
pythoninfo = psutil.virtual_memory() print(u'电脑总内存:%.4f GB' % (float(info.total) / 1024 / 1024 / 1024)) print(u'当前使用的总内存:%.4f GB' % (float(info.used) / 1024 / 1024 / 1024)) print(u'当前使用的总内存占比:%.4f' % info.percent)
获得的结果感觉和top结果比起来大差不差,能够粗略判断问题
参考:python如何获取系统内存占用信息-Python学习网
查看 Python程序或对象的内存占用_qq_40723803的博客-CSDN博客_python查看程序内存占用
C++// 实时获取程序占用的内存,单位:kb。
size_t physical_memory_used_by_process()
{
FILE* file = fopen("/proc/self/status", "r");
int result = -1;
char line[128];
while (fgets(line, 128, file) != nullptr) {
if (strncmp(line, "VmRSS:", 6) == 0) {
int len = strlen(line);
const char* p = line;
for (; std::isdigit(*p) == false; ++p) {}
line[len - 3] = 0;
result = atoi(p);
break;
}
}
fclose(file);
return result;
}
结果也大差不差,还有一些高级的方法,不过我就没有尝试了,可以看参考学习学习
参考:
在 C++ 中实时获取程序占用的内存量 - 阅微堂
C++不用工具,如何检测内存泄漏? - 知乎
C/C++内存泄漏及检测 - 吴秦 - 博客园



