前提:

centos 已经安装好Systemtap—–见其他文章

 


http://blog.yufeng.info/archives/747

<span style="font-family: Verdana, &quot;BitStream vera Sans&quot;, Tahoma, Helvetica, sans-serif; font-size: 12px; font-style: normal; font-weight: normal; background-color: rgb(255, 255, 255);"><font color="#ff0000" style="background-color: inherit;">这个脚本会每隔设定的时间打印出TOP 20切换最多的进程和他的pid</font></span>
vi cswmon.stp
#! /usr/bin/env stap
#
#

global csw_count
global idle_count

probe scheduler.cpu_off {
  csw_count[task_prev, task_next]++
  idle_count+=idle
}

function fmt_task(task_prev, task_next)
{
   return sprintf("%s(%d)->%s(%d)",
                                task_execname(task_prev), 
                                task_pid(task_prev), 
                                task_execname(task_next), 
                                task_pid(task_next))
}

function print_cswtop () {
  printf ("%45s %10s\n", "Context switch", "COUNT")
  foreach ([task_prev, task_next] in csw_count- limit 20) {
    printf("%45s %10d\n", fmt_task(task_prev, task_next), csw_count[task_prev, task_next])
  }
  printf("%45s %10d\n", "idle", idle_count)

  delete csw_count
  delete idle_count
}

probe timer.s($1) {
  print_cswtop ()
  printf("--------------------------------------------------------------\n")
}
 
#####

&nbsp;
# stap cswmon.stp 5
                               Context switch      COUNT
                swapper(0)->systemtap/11(908)        500
                systemtap/11(908)->swapper(0)        498
                swapper(0)->fct1-worker(2492)         50
                fct1-worker(2492)->swapper(0)         50
                swapper(0)->fct0-worker(2191)         50
                fct0-worker(2191)->swapper(0)         50
                      swapper(0)->bond0(3432)         50
                      bond0(3432)->swapper(0)         50
                      stapio(879)->swapper(0)         26
                      swapper(0)->stapio(879)         25
                      stapio(879)->swapper(0)         19
                      swapper(0)->stapio(879)         17
                   swapper(0)->watchdog/9(31)          5
                   watchdog/9(31)->swapper(0)          5
                    swapper(0)->mysqld(18346)          5
                    mysqld(18346)->swapper(0)          5
                  swapper(0)->watchdog/13(43)          5
                  watchdog/13(43)->swapper(0)          5
                  swapper(0)->watchdog/14(46)          5
                  watchdog/14(46)->swapper(0)          5
                                         idle        859
--------------------------------------------------------------
我们可以看到进程从哪里切换到哪里,并且发生了多少次, 最后一行,我打印出来idle的次数,也就是说这时候系统没啥事情做,就切换到idle(0)这个进程去休息去了。