[英]Detecting memory running low BEFORE allocations start failing on Windows
We have an application that could potentially allocate a large number of small objects (depending on user input). 我们有一个可能会分配大量小对象的应用程序(取决于用户输入)。 Sometimes the application runs out of memory and effectively crashes.
有时,应用程序会耗尽内存并导致崩溃。
However, if we knew that memory allocations were becoming tight there are some lower-priority objects which could be destroyed and thereby allow us to gracefully degrade the user results. 但是,如果我们知道内存分配变得紧张,那么可以销毁一些优先级较低的对象,从而使我们能够优雅地降低用户结果。
What's the best way to detect that memory for a process is running low before calls to 'new' actually fail? 在调用“new”实际上失败之前,检测进程内存的最佳方法是什么? We could call API functions like
GetProcessWorkingSetSize()
or GetProcessMemoryInfo()
but how do you know when the limits on a given machine are being reached (eg with 80% of maximum allocations)? 我们可以调用像
GetProcessWorkingSetSize()
或GetProcessMemoryInfo()
这样的API函数,但是你怎么知道什么时候达到给定机器的限制(例如80%的最大分配)?
If it's a 32-bit process then you would want to ensure that you don't use more than 1.6GB, which is 80% of 2.0GB, the max allowed for your process. 如果它是一个32位进程,那么您需要确保不要使用超过1.6GB,这是2.0GB的80%,这是您的进程允许的最大值。 Calling
GlobalMemoryStatusEx
will fill in the struct MEMORYSTATUSEX.ullAvailVirtual
, when this is only 400MB available (or less) then you are at your threshold. 调用
GlobalMemoryStatusEx
将填充结构MEMORYSTATUSEX.ullAvailVirtual
,当这个只有400MB可用(或更少)时,你就达到了你的门槛。
Check this answer Win32/MFC: How to find free memory (RAM) available? 检查此答案Win32 / MFC:如何找到可用的空闲内存(RAM)? .
。
You need to periodically find available free memory and stop allocating at some limit. 您需要定期查找可用的可用内存并在某个限制内停止分配。 As explained in above referred answer, you can use
GlobalMemoryStatusEx
, and/or VirtualQueryEx
. 如上面提到的答案中所述,您可以使用
GlobalMemoryStatusEx
和/或VirtualQueryEx
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.