开发者

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

开发者 https://www.devze.com 2023-01-31 22:46 出处:网络
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

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开发者_如何学Go 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.


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.


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消