当系统响应缓慢时, 一般会用 top 或 uptime 命令查看系统负载是否过高. 例如输入 uptime 命令显示如下图, 其中 23:47:19 表示现在的时间, up 260 days,14:39 表示系统运行了多久, 1 user 表示当前登录用户数, 最重要的是 load average, 有三个数值, 分别表示过去 1 分钟, 5 分钟, 15 分钟系统的负载. 系统负载的英文解释为:
System load averages is the average number of processes that are either in a runnable or uninterruptable state. A process in a runnable state is either using the CPU or waiting to use the CPU. A
process in uninterruptable state is waiting for some I/O access, eg waiting for disk. The averages are taken over the three time intervals. Load averages are not normalized for the number of
CPUs in a system, so a load average of 1 means a single CPU system is loaded all the time while on a 4 CPU system it means it was idle 75% of the time.
系统负载表示每分钟处于可运行状态 (运行态和就绪态) 以及不可中断状态 (等待 io) 的进程数目, 且没有做归一化处理.
图 1 uptime 命令显示图
当平均负载等于 CPU 核数时是比较合理的状态, 不会存在进程等待且也不会有 CPU 空闲浪费, 查看 CPU 核数的命令如下:
grep 'model name' /proc/cpuinfo | wc -l
uptime 命令过去 1 分钟, 5 分钟, 15 分钟的负载隐含了系统负载的变化趋势, 假如这三个指标的值差不多, 说明系统比较稳定, 假如过去 1 分钟的负载比过去 15 分钟大很多, 说明系统负载在增加, 反之, 则说明负载在减小.
平均负载和 CPU 使用率不是一个概念, 平均负载高不能说明 CPU 使用率高, 因为平均负载除了包括正在使用 CPU 的进程, 还包括在等待 CPU 的进程和等待 io 的进程.
CPU 使用率表示单位时间 CPU 的利用情况, CPU 使用率和平均负载的关系有三个场景:
CPU 密集型进程, 大量使用 CPU 会使 CPU 利用率和平均负载都增高.
IO 密集型进程, 会使平均负载增高但 CPU 使用率不一定会增高.
大量等待 CPU 的进程调度会使平均负载增高, CPU 使用率也会增高
可使用 stress 模拟这三种情况, stress 为 Linux 下的压测工具, 并用 mpstat 和 pidstat 查看根源, mpstat 显示 CPU 的使用情况, pidstat 监视 Linux 任务的统计信息, 安装如下:
yum install stress sysstat
stress 命令常用参数如下:
- -c, --CPU N
- spawn N workers spinning on sqrt()
- -i, --io N
- spawn N workers spinning on sync()
- -t, --timeout N
- timeout after N seconds
1. 用 stress 模拟 CPU 密集型进程
用 uptime 查看负载
用 mpstat 查看 CPU 使用情况, 如下, 其中 - P 的含义为
-P { CPU [,...] | ON | ALL }
Indicate the processor number for which statistics are to be reported. CPU is the processor number. Note that processor 0 is the first processor. The ON keyword indicates that statistics
are to be reported for every online processor, whereas the ALL keyword indicates that statistics are to be reported for all processors. 表示显示哪个处理器的使用情况. 5 表示统计间隔为 5s
可以看到 CPU 使用率很高, pidstat 查看具体占用 CPU 的进程, 进程 stress 占的 CPU 达到 99%,-u 的含义为 Report CPU utilization,5 表示间隔 5 秒, 1 表示输出一组数据就停止, 假如不加 1, 则会一直输出.
2.stress 模拟 io 密集型进程
uptime 查看负载, 可以看到负载已经很高(单核 CPU)
mpstat 查看负载升高原因, 可以看到 CPU0 的 iowait 高达 88.31%, 说明 CPU 有大量的时间在等待磁盘 io, 负载是由 io 进程导致, iowait 含义:%iowait
Show the percentage of time that the CPU or CPUs were idle during which the system had an outstanding disk I/O request.
定位具体的进程, 可以看到是 stress-ng-hdd,wait 含义
Percentage of CPU spent by the task while waiting to run.
3.stress 模拟大量进程场景
uptime 查看负载
mpstat 可以看到 CPU 利用率已经很高
pidstat 查看每个进程的 CPU 使用情况, 四个 stress 进程均在有较高的百分比在等待 CPU(%wait)
当 uptime 负载较高时, 可能是 CPU 使用率较高, 也可能是 io 进程较多, 可以用 mpstat 查看 CPU 使用情况, 并用 pidstat 查看定位具体进程
来源: http://www.bubuko.com/infodetail-2865405.html