CPU 上下文切换

CPU 上下文切换

作者:赵坤

CPU 上下文

CPU 上下文是 CPU 在运行任何任务前,必须的依赖环境。在每个任务运行前,CPU 需要知道任务从哪里加载、又从哪里开始运行,所以这些环境通常包括 CPU 寄存器和程序计数器等。

查看系统上下文切换情况

可以使用 vmstat 查询:

# 每隔 5 秒查询一次
$ vmstat 5
procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st
0  0    256 170532 136656 3361432    0    0    38    53  189  557  6  2 92  0  0
0  0    256 170060 136668 3362284    0    0     0    62  441  785  2  1 97  0  0
0  0    256 170320 136676 3362360    0    0     0    13  706 1002  3  1 97  0  0

cs:每秒上下文切换的次数

查看进程上下文切换情况

使用 pidstat 查看:

$ sudo apt install sysstat
$ pidstat -w 5
Linux 5.4.0-42-generic (zk) 	2020年08月31日 	_x86_64_	(4 CPU)

23时26分46秒   UID       PID   cswch/s nvcswch/s  Command
23时26分51秒     0         1      2.19      0.00  systemd
23时26分51秒     0         9      0.20      0.00  ksoftirqd/0
23时26分51秒     0        10     17.13      0.00  rcu_sched
23时26分51秒     0        11      0.20      0.00  migration/0
  • cswch,表示每秒自愿上下文切换(voluntary context switches)的次数,是指进程无法获取所需资源,导致的上下文切换。I/O、内存资源不足,容易发生。
  • nvcswch,表示每秒非自愿上下文切换(non voluntary context switches)的次数,指进程由于时间片已到等原因,被系统强制调度,进而发生的上下文切换。进程数量多,容易发生。