找出哪些任务正在产生大量的在Linux上下文切换

根据vmstat,我的Linux服务器(2xCore2 Duo 2.5 GHz)每秒钟处理大约20k个上下文切换。

# vmstat 3 procs -----------memory---------- ---swap-- -----io---- -system-- ----cpu---- rb swpd free buff cache si so bi bo in cs us sy id wa 2 0 7292 249472 82340 2291972 0 0 0 0 0 0 7 13 79 0 0 0 7292 251808 82344 2291968 0 0 0 184 24 20090 1 1 99 0 0 0 7292 251876 82344 2291968 0 0 0 83 17 20157 1 0 99 0 0 0 7292 251876 82344 2291968 0 0 0 73 12 20116 1 0 99 0 

…但uptime显示小负载: load average: 0.01, 0.02, 0.01 top不显示任何CPU使用率高的进程。

我如何找出究竟是什么产生这些上下文切换? 哪个进程/线程?

我试图分析pidstat输出:

 # pidstat -w 10 1 12:39:13 PID cswch/s nvcswch/s Command 12:39:23 1 0.20 0.00 init 12:39:23 4 0.20 0.00 ksoftirqd/0 12:39:23 7 1.60 0.00 events/0 12:39:23 8 1.50 0.00 events/1 12:39:23 89 0.50 0.00 kblockd/0 12:39:23 90 0.30 0.00 kblockd/1 12:39:23 995 0.40 0.00 kirqd 12:39:23 997 0.60 0.00 kjournald 12:39:23 1146 0.20 0.00 svscan 12:39:23 2162 5.00 0.00 kjournald 12:39:23 2526 0.20 2.00 postgres 12:39:23 2530 1.00 0.30 postgres 12:39:23 2534 5.00 3.20 postgres 12:39:23 2536 1.40 1.70 postgres 12:39:23 12061 10.59 0.90 postgres 12:39:23 14442 1.50 2.20 postgres 12:39:23 15416 0.20 0.00 monitor 12:39:23 17289 0.10 0.00 syslogd 12:39:23 21776 0.40 0.30 postgres 12:39:23 23638 0.10 0.00 screen 12:39:23 25153 1.00 0.00 sshd 12:39:23 25185 86.61 0.00 daemon1 12:39:23 25190 12.19 35.86 postgres 12:39:23 25295 2.00 0.00 screen 12:39:23 25743 9.99 0.00 daemon2 12:39:23 25747 1.10 3.00 postgres 12:39:23 26968 5.09 0.80 postgres 12:39:23 26969 5.00 0.00 postgres 12:39:23 26970 1.10 0.20 postgres 12:39:23 26971 17.98 1.80 postgres 12:39:23 27607 0.90 0.40 postgres 12:39:23 29338 4.30 0.00 screen 12:39:23 31247 4.10 23.58 postgres 12:39:23 31249 82.92 34.77 postgres 12:39:23 31484 0.20 0.00 pdflush 12:39:23 32097 0.10 0.00 pidstat 

看起来像一些postgresql任务是每秒> 10上下文swiches,但它并不总是达到20K无论如何。

任何想法如何深入挖掘一个答案?

那么,相当有趣的情况。 尝试观察watch -tdn1 cat /proc/interrupts 。 你有看到有什么宝贵的变化吗?

尝试使用

pidstat -wt

't'选项也显示线程。 这可能是一个正在执行上下文切换的线程。

上下文切换正常。 一个进程被分配给一个时间量,如果它完成了(或者由于需要资源而暂停),它所要做的事情可以让处理器去。

这就是说要计算完成多less上下文切换(它变成了一个stackoverflow.com的答案),需要内部的内核调度()命令来写入进程表。 如果你编写你自己的内核,你就不会看到这样的东西,但是这很困难。

powertop可以告诉你一个进程唤醒CPU的频率。