CPU上下文切换包括进程上下文切换、线程上下文切换及中断上下文切换,当任务进行io或发生时间片事件及发生中断(如硬件读取完成)时,就会进入内核态,发生CPU上下文切换。缓存
过多的上下文切换会致使将大量CPU时间浪费在寄存器、内核栈以及虚拟内存的保存和恢复上,致使系统总体性能降低。能够用vmstat查看系统的总体上下文切换状况,以下图1,空闲系统的上下文切换次数cs(context switch)为100多,中断次数in(interrupt)为100多,在运行态r(running or runable)的进程数为2,在阻塞态的进程数b为0。多线程
图1 空闲系统上下文切换和中断状况性能
案例:咱们用sysbench来模拟多线程频繁上下文切换的场景,并用vmstat、pidstat和/proc/interrupts来分析定位具体的线程。ui
用sysbench模拟10个线程,运行300s来观察线程切换的频繁场景,以下图2所示。线程
图2 大量线程切换场景模拟指针
用vmstat查看系统总体的上下文切换和中断状况,以下图3,可看到cs和in的数目和空闲的时候比增长了不少。blog
图3 系统总体上下文切换状况进程
发现系统切换状况比较频繁,能够用pidstat查看具体切换比较频繁的线程,命令:pidstat -w -t 1,含义以下,事件
-w Report task switching activity (kernels 2.6.23 and later only). The following values may be displayed:内存
cswch/s
Total number of voluntary context switches the task made per second. A voluntary context switch occurs when a task blocks because it requires a resource that is unavailable.
每秒自愿上下文切换次数,如等待io等。
nvcswch/s
Total number of non voluntary context switches the task made per second. A involuntary context switch takes place when a task executes for the duration of its time slice and then is
forced to relinquish the processor.
每秒非自愿上下文切换次数,如时间片用完切换。
-t展现具体的线程状况。
结果以下图4所示,能够看到,切换频繁的线程是sysbench
图4 线程切换状况