win7装什么杀毒软件好:DELPHI 清理释放内存小代码

来源:百度文库 编辑:中财网 时间:2024/04/28 05:00:14
2007-04-05 22:45
DELPHI清理释放内存小代码
procedure ClearMemory;
begin
if Win32Platform = VER_PLATFORM_WIN32_NT then
begin
SetProcessWorkingSetSize(GetCurrentProcess, $FFFFFFFF, $FFFFFFFF);
Application.ProcessMessages;
end;
end;
上面这段代码是我在网上看到的,下面应 xb3320       的要求解释一下:
本段代码的核心是调用了NT内核的API函数SetProcessWorkingSetSize ,所以,在调用该函数之前要判断该系统是否属于NT内核,ProcessMessages 的作用是让应用程序能继续响应其他消息。
API函数SetProcessWorkingSetSize 在Delphi中的声明如下:
function SetProcessWorkingSetSize(hProcess: THandle;
dwMinimumWorkingSetSize, dwMaximumWorkingSetSize: DWORD): BOOL; stdcall;
{$EXTERNALSYM SetProcessWorkingSetSize}
说明
设置操作系统实际划分给进程使用的内存容量
返回值
BOOL,True表示成功,False表示失败。
参数表
参数类型及说明
hProcessTHandle,指定一个进程的句柄
dwMinimumWorkingSetSizeDWORD,用于装载最小进程容量的一个变量(最小占用内存值)
dwMaximumWorkingSetSizeDWORD,用于装载最大进程容量的一个变量(最大占用内存值)
适用平台
Windows NT
我在Delphi中测试了一下,在任务管理器中查看了执行该函数前后的情况,发现所谓的“清理”“释放”内存其实就是把空闲的内存放到虚拟内存中去。并且造成了页面错误数增加。
关于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.
当你加大运行空间给应用程序,你能够得到的物理内存取决于系统,这会造成其他应用程序降低性能或系统总体降低性能,这也可能导致请求物理内存的操作失败,例如:建立 进程,线程,内核池,就必须小心的使用该函数。
所以,实际上使用该函数并不能提高什么性能,也不会真的节省内存。因为他只是暂时的将应用程序占用的内存移至虚拟内存,一旦应用程序被激活或者有操作请求时,这些内存又会被重新调入。如果你强制使用该方法来 设置程序占用的内存,那么可能在一定程度上反而会降低系统性能,因为系统需要频繁的进行内存和硬盘间的页面交换。但是,该函数还是有很大的用处的,当我们的应用程序刚刚加载完成时,可以使用该操作一次,来将加载过程不需要的代码放到虚拟内存,这样,程序加载完毕后,保持较大的可用内存。还有,程序运行到一定时间后或程序将要被闲置时,可以使用该函数来交换占用的内存到虚拟内存。