Windows API 学习-SetProcessWorkingSetSize函数

SetProcessWorkingSetSize,从这个函数的名字上中文翻译来看,设置进程工作集。这里提到了一个名词,工作集。工作集可以如下定义:一个进程当前正在占用的页面的集合就是它的工作集。页面是虚拟地址按照固定大小划分成的若干单元,页面地址经过映射,得到实际的物理地址,但是,不是所有虚拟地址页面都对应着物理地址,我们可以把一些很久没有使用的内存中的数据写到外存,当使用时,进行缺页中断,再写入内存。

现在回到这个API,而这个API干的事情就是使系统回收进程当前没有的使用的内存,并把数据写到外存。

MSDN上,函数定义如下:

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

hProcess [in]

A handle to the process whose working set sizes is to be set.

……

dwMinimumWorkingSetSize [in]

The minimum working set size for the process, in bytes. The virtual memory manager attempts to keep at least this much memory resident in the process whenever the process is active.

……

dwMaximumWorkingSetSize [in]

The maximum working set size for the process, in bytes. The virtual memory manager attempts to keep no more than this much memory resident in the process whenever the process is active and available memory is low.

……

If both dwMinimumWorkingSetSize and dwMaximumWorkingSetSize have the value (SIZE_T)–1, the function removes as many pages as possible from the working set of the specified process.

Return value

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

SetProcessWorkingSetSize函数只是暂时的改变应用程序占用的内存,一旦应用程序被激活或者有操作请求时,这些内存又会被重新占用.如果你强制使用该方法来设置 程序占用的内存,那么可能在一定程度上反而会降低系统性能,因为发生缺页中断的频率变高,系统需要频繁的进行内存和硬盘间的页面交换。

 

给出一段简单的代码,打开notepad进程,并调用SetProcessWorkingSetSize函数调节占用的工作集,同时把我们可以打开资源监视器,监视该进程设置成功。注意上文中的一句,当进程被激活或者有操作请求时,这些内存又会被重新占用。

code:

 

未设置之前,notepad占用的物理内存:

setbefore

设置后,(1000-2000KB):

setafter

可以看到,设置成功。当我们点击notepad或者在notepad窗口上进行编辑,工作集又会明显增加。

(ps:经过了一番修改,现在的认识多少有些靠谱,原来的认识还真是无知到了一定程度。看了看虚拟内存这一块,现在是有些理解了这个API,不同的观点欢迎讨论)

posted on 2012-11-09 11:49  algoCG  阅读(949)  评论(0编辑  收藏  举报

导航