> For the complete documentation index, see [llms.txt](https://pshizhsysu.gitbook.io/linux/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://pshizhsysu.gitbook.io/linux/other/cpuyu-nei-cun.md).

# CPU与内存

本节主要介绍linux下CPU与内存的监控命令

## top命令

```
top - 09:24:20 up 23:49,  1 user,  load average: 0.02, 0.05, 0.00
Tasks: 132 total,   1 running,  61 sleeping,   0 stopped,   0 zombie
%Cpu(s):  0.2 us,  0.5 sy,  0.0 ni, 99.0 id,  0.3 wa,  0.0 hi,  0.0 si,  0.0 st
KiB Mem :  4016436 total,  2045928 free,  1296152 used,   674356 buff/cache
KiB Swap:        0 total,        0 free,        0 used.  2349904 avail Mem 

   PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND                                                                                          
   736 root      20   0  127156  51588  23972 S   2.0  1.3  21:44.65 kube-controller                                                                                  
  1009 root      20   0  324196 188688  31260 S   1.0  4.7  16:43.87 kube-apiserver                                                                                   
   737 root      20   0   43032  22640  13396 S   0.7  0.6   6:41.29 kube-scheduler
```

> 第一行

见 Reference \[3]

> 第三行

* us：user，用户进程占用的cpu百分比
* sy：system，系统进程占用的cpu百分比
* ni：
* id：idle，cpu空闲百分比
* wa：wait，io等待占用的cpu百分比
* hi：hard interupt，硬中断占用的cpu百分比
* si：soft interupt，软中断占用的cpu百分比

> 第四行

见free命令

> 第七行

* PID    ：进程ID
* USER   ：进程所属用户
* PR     ：priority，进程优先级，值越大优先级越高
* NI     ：nice值，正值表示低优先级，负值表示高优先级
* VIRT   ：virtual，进程使用的虚拟内存总量，单位Ki。VIRT=SWAP+RES
* RES    ：resident，进程的常驻内存总量，即进程使用的、未被换出的内存大小，单位Ki。RES=CODE+DATA
* SHR    ：shared，进程使用的共享内存大小，单位Ki
* S      ：status，进程状态。D=不可中断的睡眠状态 R=运行 S=睡眠 T=跟踪/停止 Z=僵尸进程
* CPU%   ：上次更新到现在，进程使用的CPU使用百分比
* MEM%   ：上次更新到现在，进程使用的物理内存百分比，MEM%=RES/total
* TIME+  ：系统启动后，进程使用的CPU时间总计。格式为：`hour:min:second`
* COMMAND：进程命令

## free命令

```
$ free -w -b
              total        used        free      shared     buffers       cache   available
Mem:     4112830464  1353334784  2061275136    17530880           0   698220544  2380181504
Swap:             0           0           0
```

* total：系统物理内存大小
* used：已使用的物理内存大小（包含了shared）
* free：空闲的物理内存大小（不包括buffer与cache）
* shared：已使用的共享内存大小
* buffers：缓冲区大小（可被系统回收给应用程序用）
* cache：缓存大小（可被系统回收给应用程序用）
* available：应用程序可用的内存大小，一般我们说主机还有多少内存可用指的是这个值

几种关系如下：

```
total = used + free + buffer + cache
available <= free + buffer + cache              # 因为系统的部分page或buffer是无法回收的
```

## 使用指南

```
top -p pid   # 查看某个进程的物理内存使用量（RES那一列，单位为Ki）或百分比（MEM%那一列）
```

## Reference

\[1] <http://www.cnblogs.com/peida/archive/2012/12/24/2831353.html>

\[2] <http://www.voidcn.com/article/p-mqeigfuz-bqu.html>

\[3] <http://www.ruanyifeng.com/blog/2011/07/linux_load_average_explained.html>
