简体   繁体   English

使用C ++查找32位Linux中进程可用的剩余内存

[英]Find remaining memory available to a process in 32 bit Linux using C++

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. 我的C ++程序缓存了许多对象,并且在每个主要API调用的开始,我想确保至少有500 MB可用于该API调用。 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). 我可能用完了RAM +交换空间(考虑具有1 GB RAM + 1 GB SWAP文件的系统),或者我在处理过程中可能用完了虚拟地址(我可能已经在总4GB中使用了3.7 GB地址空间)。 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). 我很难估计要缓存的数据量,但是如果它成为问题,我可以清除其中的一些数据,然后反复进行,直到在系统或地址空间中有500 MB可用空间(以瓶颈为准)为止。 So my requirements are to find in C++ on 32 bit Linux: 所以我的要求是在32位Linux上的C ++中找到:

A) Find how much RAM + SWAP space is free. A)查找多少RAM + SWAP空间可用。
B) How much user space address space is available to my process. B)我的进程有多少用户空间地址空间可用。
C) How much Virtual Memory the process is already using. C)该进程已使用了多少虚拟内存。 Consider it similar to 'Commit Size' or 'Working Set Size' of a process on Windows. 认为它类似于Windows上进程的“提交大小”或“工作集大小”。

Any answers would be greatly appreciated. 任何答案将不胜感激。

Look at /proc/vmstat there is a lot of information about the system wide memory. 查看/ proc / vmstat,有很多有关系统范围内存的信息。

The /proc//maps will give you a lot of information about your process memory layout. / proc // maps将为您提供有关进程内存布局的大量信息。

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. 我对您的缓存类一无所知,但是如果这些对象很小,您可能已经覆盖了new / delete运算符。 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. 在32位上,它可能会失败,因为堆可能会碎片化,但是如果可以,请确保此时有足够的内存。

Take a look at the source for the vmstat : here . 看一下vmstat的来源: 这里 Then search for domem() function, which gather all information about the memory (occupied and free). 然后搜索domem()函数,该函数收集有关内存的所有信息(已占用和空闲)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM