Thinking_Out_Loud

Linux进程内存耗用的表述:VSS/RSS/PSS/USS

2018-09-19

背景

小白如我,写完程序想看看内存占用多少,打开了top却不知道看哪一项为准。

是什么?

一开始我也是很懵。

先一起看看它们的全称和释义:

VSS(VSZ) - Virtual Set Size
The Virtual Set Size is a memory size assigned to a process ( program ) during the initial execution. The Virtual Set Size memory is simply a number of how much memory a process has available for its execution.

VSS即由进程视角看到的所有可访问的内存大小,包括被置入交换区的部分,是由系统分配的虚拟内存。

RSS - Resident Set Size
RSS is a memory currently used by a process. This is a actual number in kilobytes of how much RAM the current process is using.

RSS则是进程在内存中实际占有的物理内存大小,正如其名是常驻集大小,所以不包括被置换进交换区的部分。

PSS - Proportional Set Size
Pss is the amount of memory shared with other processes, accounted in a way that the amount is divided evenly between the processes that share it. This is memory that would not be released if the process was terminated, but is indicative of the amount that this process is “contributing”.

由于不同进程间会在内存中共同享有一些内存,如共享库,所以PSS可以综合考虑共享进程数,将共享库的内存占用按比例算入到进程名下。

USS - Unique Set Size
Uss is the set of pages that are unique to a process. This is the amount of memory that would be freed if the application was terminated right now.

USS则是进程单独占用的内存,如堆和栈都是不能给别人看的。

The unshared memory (USS) plus a process’s proportion of shared memory is reported as the PSS (Proportional Set Size). The USS and PSS only include physical memory usage. They do not include memory that has been swapped out to disk.

又根据上面smem(8)的描述可知,USS和PSS都不包含被置入交换区的部分。

所以一般来说有VSS >= RSS >= PSS >= USS

一个计算例子

假设有进程A,程序大小500K,链接共享库大小2500K,现在进程实际加载了共享库的1000K以及自身程序的400K,且堆栈大小200K,其中的100K被置入交换区,那么有:

1
2
3
4
VSS = 500K + 2500K + 200K = 3200K
RSS = 400K + 1000K + 100K = 1500K
PSS = 400K + 1000K/2 + 100K = 1000K # 假设两个进程使用共享库
USS = 400K + 100K = 500K

使用

  • 因为VSS还统计了进程尚未在内存中使用的大小(如进程malloc后,系统并不会第一时间分配内存)所以一般不用来衡量进程的内存占用;
  • 而RSS因为将进程使用的共享库纳入统计,即使这个库能被复数进程共享,所以单独使用RSS作为测量项也会有误导性;
  • 相对于RSS,PSS更适合作为进程内存占用的衡量项,而且不用担心PSS的更新时间;
  • USS则非常适合用来采样观察进程是否发生了内存泄漏。

参考资料

  1. https://linuxconfig.org/ps-output-difference-between-vsz-vs-rss-memory-usage
  2. https://elinux.org/Android_Memory_Usage
  3. https://stackoverflow.com/questions/7880784/what-is-rss-and-vsz-in-linux-memory-management
  4. https://stackoverflow.com/questions/22372960/is-this-explanation-about-vss-rss-pss-uss-accurate
  5. https://www.jianshu.com/p/9bf36aa82f90
  6. https://linux.die.net/man/8/smem
Tags: Linux