使用 C++ 查找 32 位 Linux 中进程可用的剩余内存
我的 C++ 程序缓存了大量对象,并且在每个主要 API 调用开始时,我想确保至少有 500 MB 可用于 API 调用。我可能用完了 RAM+交换空间(考虑具有 1 GB RAM + 1 GB SWAP 文件的系统),或者我可能用完了进程中的虚拟地址。(我可能已经使用了 4GB 总量中的 3.7 GB地址空间)。对我来说,估算缓存了多少数据并不容易,但如果它成为问题,我可以清除其中的一些数据,并迭代地执行此操作,直到系统或地址空间中有 500 MB 可用(以成为瓶颈的为准)。所以我的要求是在 32 位 Linux 上用 C++ 查找:
A) 查找有多少 RAM + SWAP 空间是可用的。
B) 有多少用户空间地址空间可供我的进程使用。
C) 进程已使用多少虚拟内存。将其视为类似于 Windows 上进程的“提交大小”或“工作集大小”。
任何答案将不胜感激。
My C++ program caches lots of objects, and in beginning of each major API call, I want to ensure that there is at least 500 MB available for the API call. I may either be running out of RAM+swap space (consider system with 1 GB RAM + 1 GB SWAP file), or I may be running out of Virtual Address in my process.(I may already be using 3.7 GB out of total 4GB address space). It's not easy for me to approximate how much data I have cached, but I can purge some of it if it is becoming an issue, and do so iteratively till I have 500 MB available in system or address space (whichever is becoming bottleneck). So my requirements are to find in C++ on 32 bit Linux:
A) Find how much RAM + SWAP space is free.
B) How much user space address space is available to my process.
C) How much Virtual Memory the process is already using. Consider it similar to 'Commit Size' or 'Working Set Size' of a process on Windows.
Any answers would be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
查看 /proc/vmstat 有很多有关系统内存的信息。
/proc//maps 将为您提供有关进程内存布局的大量信息。
请注意,如果您在运行长时间作业之前检查内存,则另一个进程可能会耗尽所有可用内存,并且您的程序可能会崩溃!
我对您的缓存类一无所知,但如果这些对象非常小,您可能已经覆盖了 new/delete 运算符。通过这种方式,可以很容易地跟踪内存消耗(至少通过计算对象)
为什么不改变你的缓存策略呢?并刷新旧的未使用的对象。
另一种丑陋的方法是尝试分配几块内存,然后查看程序可以分配它,然后释放它。在 32 位上,它可能会失败,因为堆可能会碎片化,但如果它有效,那么您确定此时有足够的内存。
Look at /proc/vmstat there is a lot of information about the system wide memory.
The /proc//maps will give you a lot of information about your process memory layout.
Note that if you check the memory before running a long job, another process may eat all the available memory and your program may crash anyway !
I do not know anything about your cached classes but if these objects are quite small you probably have overridden the new/delete operators. By this it is quite easy to keep track of the memory consumption (at least by counting objects)
Why not change your cache policy ? And flush old unused object.
Another ugly way is to try to allocate several chunk of memory and see the program can allocate it, and release it after that. On 32 bits it may fail because the heap may be fragmented, but if it works you sure that you have enough memory at this time.
查看 vmstat 的源代码: 此处。然后搜索domem()函数,它收集有关内存的所有信息(占用的和空闲的)。
Take a look at the source for the vmstat : here. Then search for domem() function, which gather all information about the memory (occupied and free).