美文网首页
Linux top命令的内存参数VIRT/RES/SHR

Linux top命令的内存参数VIRT/RES/SHR

作者: CodingCode | 来源:发表于2022-04-01 08:31 被阅读0次

    我们执行top命令:

    top - 00:02:47 up 9 days,  7:52,  2 users,  load average: 0.00, 0.00, 0.00
    Tasks: 192 total,   2 running, 109 sleeping,   0 stopped,   0 zombie
    %Cpu(s): 22.2 us,  4.8 sy,  0.0 ni, 73.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
    KiB Mem : 32581132 total,  6161024 free,  1303980 used, 25116128 buff/cache
    KiB Swap:  8388604 total,  8388604 free,        0 used. 30508356 avail Mem
    
      PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND
    24290 user      20   0  308624 100764   9136 R  93.8  0.3   0:00.67 python3
        1 root      20   0  217372  10680   6980 S   0.0  0.0   2:01.09 systemd
        2 root      20   0       0      0      0 S   0.0  0.0   0:00.34 kthreadd
    

    对于每个PID都有对应的VIRT,RES,和SHR三个参数值用来描述进程的内存使用情况。具体是什么含义呢?

    下面是man top的输出:

    36. VIRT  --  Virtual Memory Size (KiB)
               The total amount of virtual memory used by the task.  It includes all code, data and shared libraries plus pages that have been swapped out and pages that have been mapped but not used.
    17. RES  --  Resident Memory Size (KiB)
               The non-swapped physical memory a task is using.
    21. SHR  --  Shared Memory Size (KiB)
               The amount of shared memory available to a task, not all of which is typically resident.  It simply reflects memory that could be potentially shared with other processes.
    

    下面是结合网上搜搜的结果后我的理解,不一定正确:

    VIRT:

    1. 就是虚拟空间大小。我也同意很多人说这个参数不重要,不需要参考。
    2. 有人说进程的虚拟空间大小不都是4G吗?0x00000000-0xffffffff吗,为什么还有这个VIRT概念。
      答:4G是理论上的进程允许地址空间,时间进程用不了这么大空间,比如绝大部分用户代码、数据、共享库都是映射到2G-3G之间的范围,剩下空间范围都是空的,没有映射。所以VIRT是指进程的可寻址空间,也就是有内容映射到的地址;抛开权限控制,就是可以访问的地址(假设你是root,那么你就可以去read这些地址),而其他地址是不能访问的,否则就会出现invalid address的进程crash。

    RES:

    1. 真正占用内存的空间。
    2. 当然是VIRT的一部分。

    SHR:

    1. 是共享的空间,例如共享内存,共享的so库等。
    2. 也是VIRT的一部分。
    3. 是不是RES的部分呢?网上有两种说法,一种认为是,一种认为不是;我认为不是,即SHR使VIRT的部分,而不是RES的部分,RES和SHR有交集,也有不同的部分。拿共享库来说明例子:
    In the case of libraries, it does not necessarily mean that the entire library is resident.
    For example, if a program only uses a few functions in a library, the whole library is mapped and
    will be counted in VIRT and SHR, but only the parts of the library file containing the functions being used will
    actually be loaded in and be counted under RES.
    

    意思是例如对于一个很大共享库(如10页)。

    1. 整个共享库全部空间全部计算入 VIRT和SHR。(VIRT=VIRT+10pages,SHR=SHR+10pages)
    2. 如果我们的进程只调用其中很小的一块代码,那么共享库中只需要把被调用到的代码(假设只有一页)加载进内存,此时RES只计算入这一页。(RES=RES+1page)
    image.png

    相关文章

      网友评论

          本文标题:Linux top命令的内存参数VIRT/RES/SHR

          本文链接:https://www.haomeiwen.com/subject/odgojrtx.html