您的位置:首页 > 编程语言 > PHP开发

使用SetProcessWorkingSetSize将物理内存的占用挪到虚拟内存里

2013-02-26 11:04 309 查看
导言:有些应用程序号称使用的内存要比其他同类的软件所耗费的内存要低非常多,实际上只是把占用物理内存的部分挪到虚拟内存里面,给用户造成一个假象。在真正性能上,该方法没有任何益处,多用于欺骗无知的用户,满足用户无知的需求。

本文部分摘录自:http://blog.csdn.net/zlt982001/article/details/466879

如何能够将占用的内存移至虚拟内存呢?

其实,你也可以,试试看把一个程序最小化到任务栏,再看看任务管理器,看到没,你的程序占用的实际内存一下子减少了,看来并不是我有什么方法能够压缩内存,而是操作系统本身就有这个机制,即当程序不使用时(最小化),操作系统会调用某些命令,来将该程序占用的内存移至虚拟内存,只保留一小部分常规代码

所以我们就看到了 这种情景,占用的内存一下子就缩小了。

那么:系统到底调用了什么指令呢?能不能在不缩小窗体的情况下来释放内存呢?

看看这个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 theVirtualLock
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 theSetProcessWorkingSetSize 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 当我们的应用程序刚刚加载完成时,可以使用该操作一次,来将加载过程不需要的代码放到虚拟内存,这样,程序加载完毕后,保持较大的可用内存。VB尤甚

2.程序运行到一定时间后或程序将要被闲置时,可以使用该命令来交换占用的内存到虚拟内存。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: