Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> 電腦軟體教學 >> 伺服器技術 >> 關於伺服器

Linux 進程切換偵測實戰:用 SystemTap 精準定位「誰在切換進程」

編輯:關於伺服器

為何要關注進程切換?

進程切換代價高昂。LMbench 測試(高端伺服器):單次切換開銷 ~8μs。對高性能伺服器不可接受。目標:在單一時間片內多做實事,而非浪費在無謂切換。

初步觀測:dstat 看現象不見本質

# dstat 1
----total-cpu-usage---- -dsk/total- -net/total- ---paging-- ---system--
usr sys idl wai hiq siq| read  writ| recv  send|  in   out | int   csw
0   0 100   0   0   0|   0     0 | 796B 1488B|  0    0 |1004  128
0   0 100   0   0   0|   0     0 | 280B  728B|  0    0 |1005  114
...

csw (context switch) ~120/s,但 dstat/vmstat 不告訴「誰在幹壞事」。

核心武器:SystemTap 腳本

#!/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(5) {
  print_cswtop()
  printf("--------------------------------------------------------------\n")
}

執行:stap cswmon.stp 5(每 5 秒輸出 Top 20)

實戰輸出解讀


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
...
idle                                                  859

清晰可見:
• 進程從哪裡切到哪裡、切換次數
• swapper(0) 即 idle 進程(PID 0)
• 最後一行 idle 計數 = 系統閒置切換到 idle 休息的次數

進階應用:生產環境持續監控

  1. 腳本部署為系統服務,定期輸出至日誌/時序資料庫。
  2. 設定告警閾值:單位時間切換次數超標、特定進程對切換佔比異常。
  3. 結合 perf sched、trace-cmd 做深度調用鏈分析。
  4. 優化方向:釘住關鍵進程 CPU 親和性、調整 nice 值、減少鎖競爭、優化中斷親和性。

結語

SystemTap 讓「誰在切換進程」從黑盒變透明。定位切換熱點 → 針對性優化 → 釋放 CPU 週期給業務邏輯,是高性能 Linux 運維的必修課。

Copyright © Windows教程網 All Rights Reserved