开发者

Returning the size of available virtual memory at run-time in C++

开发者 https://www.devze.com 2022-12-26 10:13 出处:网络
In C++ is there a predefined library function that will return the size of RAM currently available on a computer a program is being run on, at run-time?

In C++ is there a predefined library function that will return the size of RAM currently available on a computer a program is being run on, at run-time?

For instance, if an object is 4bytes, then can we divide the available virtual memory by 4 bytes to give an estimate of how many more objects could be stored by the program safely?

I have used the sizeof() function to return the size of objects within my program.

Seeing as this was frequently asked for in the helpful responses - The platform the program is running on is Wind开发者_StackOverflow中文版ows (7).

Thanks


Not in the C++ Standard Library - your operating system probably provides this facility though, via a platform-specific API.


There's nothing in the C++ standard that returns the amount of free memory available. Such a function, if available at all, would be platform-specific.


First of all size of the RAM has nothing to do with how much free virtual memory available in the process. It just that your program will slow down if the RAM is less due to frequent page faults. Also, the virtual memory will be mostly fragmented so it makes more sense to find the things such as largest continuous free memory instead of total free memory.

There are no built in C++ functions to do this you have use OS API's to get it. For example, on windows you can use the Win32 APIs to get this information.


It's platform specific, not part of the language standard.

However, there's a Windows specific API to get process memory informations: GetProcessMemoryInfo().

Additionally, virtual addressing allow processes to allocate more than total physical RAM.


In Win32 you can use

 MEMORYSTATUS st;
 ::GlobalMemoryStatus(&st);


There is no good solution for this in Windows. When a program frees a heap block, it almost always gets added to a list of free blocks. You can only discover these is by walking the heap with HeapWalk(). That's expensive and very detrimental to the operation of a multi-threaded program because you have to lock the heaps.

Also, a program almost never runs out of free virtual memory space. It first runs out of a free contiguous chunk of space that's large enough to fit the request. The sum of block sizes you get from HeapWalk is not meaningful unless you only ever make very small allocations.

The most typical reason for wanting a feature like this is because your program is routinely running out of memory. There is a very effective and cheap solution available for that problem. Two hundred bucks buys you a 64-bit version of Windows.

0

精彩评论

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