1. 程式人生 > >SetProcessWorkingSetSize() 方法使內存降低了很多(把內存放到交換區,其實會降低性能)——打開後長時間不使用軟件,會有很長時間的加載過程,原來是這個!

SetProcessWorkingSetSize() 方法使內存降低了很多(把內存放到交換區,其實會降低性能)——打開後長時間不使用軟件,會有很長時間的加載過程,原來是這個!

相關 opera UNC 情況下 縮小 ole careful however guarantee

在項目中對程序性能優化時,發現用SetProcessWorkingSetSize() 方法使內存降低了很多,於是查閱了相關的資料如下:

我的程序為什麽能夠將占用的內存移至虛擬內存呢?

其實,你也可以,試試看把一個程序最小化到任務欄,再看看任務管理器。看到沒,你的程序占用的實際內存一下子減少了,看來並不是我有什麽方法能夠壓縮內存,而是操作系統本身就有這個機制,即當程序不使用時(最小化),操作系統會調用某些命令,來將該程序占用的內存移 至虛擬內存,只保留一小部分常規代碼。所以我們就看到了 這種情景,占用的內存一下子就縮小了。

那麽:系統到底調用了什麽指令呢?能不能在不縮小窗體的情況下來釋放內存呢?

看看這個API:SetProcessWorkingSetSize


BOOL SetProcessWorkingSetSize(
HANDLE hProcess,
SIZE_T dwMinimumWorkingSetSize,
SIZE_T dwMaximumWorkingSetSize
);

將 2個 SIZE_T 參數設置為 -1 ,即可以使進程使用的內存交換到虛擬內存,只保留一小部分代碼。

這是從MSDN摘下的原話

Using the SetProcessWorkingSetSize function to set an application‘s minimum and maximum working set sizes does not guarantee that the requested memory will be reserved, or that it will remain resident at all times. When the application is idle, or a low-memory situation causes a demand for memory, the operating system can reduce the application‘s working set. An application can use the VirtualLock function to lock ranges of the application‘s virtual address space in memory; however, that can potentially degrade the performance of the system.

使用這個函數來設置應用程序最小和最大的運行空間,只會保留需要的內存。當應用程序被閑置或系統內存太低時,操作系統會自動調用這個機制來設置應用程序的內存。應用程序也可以使用 VirtualLock 來鎖住一定範圍的內存不被系統釋放。

When you increase the working set size of an application, you are taking away physical memory from the rest of the system. This can degrade the performance of other applications and the system as a whole. It can also lead to failures of operations that require physical memory to be present; for example, creating processes, threads, and kernel pool. Thus, you must use the SetProcessWorkingSetSize function carefully. You must always consider the performance of the whole system when you are designing an application.

當你加大運行空間給應用程序,你能夠得到的物理內存取決於系統,這會造成其他應用程序降低性能或系統總體降低性能,這也可能導致請求物理內存的操作失敗,例如:建立 進程,線程,內核池,就必須小心的使用該函數。

---------------------------------------------------------------------------------------------------------

事實上,使用該函數並不能提高什麽性能,也不會真的節省內存。

因為他只是暫時的將應用程序占用的內存移至虛擬內存,一旦,應用程序被激活或者有操作請求時,這些內存又會被重新占用。如果你強制使用該方法來 設置程序占用的內存,那麽可能在一定程度上反而會降低系統性能,因為系統需要頻繁的進行內存和硬盤間的頁面交換。

https://blog.csdn.net/hellokandy/article/details/74990122

SetProcessWorkingSetSize() 方法使內存降低了很多(把內存放到交換區,其實會降低性能)——打開後長時間不使用軟件,會有很長時間的加載過程,原來是這個!