Delphi清理释放本程序内存的代码

zt    http://www.abcxd.com/delphi/abcxddelphi/delphiZY/SetProcessWorkingSetSize.html


明生注:请注意中间那段揭密文章,来按照自己的个人意愿来执行。不要贪一时的快感而影响稳定性

在WinXp,Win2K中应用此方法,不显示主窗体一直运行的程序最佳。以前程序占用11M内存,我用动态创建窗口的方法只能减少不到100K,应用此方法后内存占用只有496K。把下面的过程放到一个Timer中,每隔一段时间执行一次,如30秒。 

{
************************************
* Clear Memory
* From Muse2008
************************************
}
procedure ClearMemory;
begin
        if Win32Platform = VER_PLATFORM_WIN32_NT then
        begin
                SetProcessWorkingSetSize(GetCurrentProcess, $FFFFFFFF, $FFFFFFFF);
                Application.ProcessMessages;
        end;
end; 

将物理内存的占用挪到虚拟内存里-----揭密篇
那么我的程序为什么能够将占用的内存移至虚拟内存呢?
其实,你也可以,试试看把一个程序最小化到任务栏,再看看任务管理器,看到没,你的程序占用的实际内存一下子减少了,看来并不是我有什么方法能够压缩内存,而是操作系统本身就有这个机制,即当程序不使用时(最小化),操作系统会调用某些命令,来将该程序占用的内存移至虚拟内存,只保留一小部分常规代码
所以我们就看到了 这种情景,占用的内存一下子就缩小了。
那么:系统到底调用了什么指令呢?能不能在不缩小窗体的情况下来释放内存呢?
看看这个API                       SetProcessWorkingSetSize
这是从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.
当你加大运行空间给应用程序,你能够得到的物理内存取决于系统,这会造成其他应用程序降低性能或系统总体降低性能,这也可能导致请求物理内存的操作失败,例如:建立进程,线程,内核池,就必须小心的使用该函数。
========================
事实上,使用该函数并不能提高什么性能,也不会真的节省内存。
因为他只是暂时的将应用程序占用的内存移至虚拟内存,一旦,应用程序被激活或者有操作请求时,这些内存又会被重新占用。如果你强制使用该方法来设置程序占用的内存,那么可能在一定程度上反而会降低系统性能,因为系统需要频繁的进行内存和硬盘间的页面交换。

BOOL SetProcessWorkingSetSize(
  HANDLE hProcess,
  SIZE_T dwMinimumWorkingSetSize,
  SIZE_T dwMaximumWorkingSetSize
);
将 2个  SIZE_T  参数设置为 -1 ,即可以使进程使用的内存交换到虚拟内存,只保留一小部分代码

当然,该函数也并非无一是处,
1 。当我们的应用程序刚刚加载完成时,可以使用该操作一次,来将加载过程不需要的代码放到虚拟内存,这样,程序加载完毕后,保持较大的可用内存。

2.程序运行到一定时间后或程序将要被闲置时,可以使用该命令来交换占用的内存到虚拟内存。
最后,附上易语言 调用的API 代码
.版本 2
.DLL命令 调整内存, 整数型, , "SetProcessWorkingSetSize"
    .参数 句柄, 整数型
    .参数 最小值, 整数型
    .参数 最大值, 整数型
.版本 2
.子程序 _按钮1_被单击
调整内存 (-1, -1, -1)

偷省下事.其实第一个参数应该用 GetCurrentProc

 

猜你喜欢

转载自blog.csdn.net/MouGang/article/details/38292729
今日推荐