如何實時監測進程調度累計的 runtime
構想
進程的調度數據可通過 proc 文件系統查看,/prod/${pid}/sched 中的參數,對性能優化來說很有參考意義,比如 1 號進程的數據如下:
systemd (1, #threads: 1)
-------------------------------------------------------------------
se.exec_start : 269493519.475163 #最近被調度到開始執行時間,ns
se.vruntime : 939.800291 #虛擬運行時間
se.sum_exec_runtime : 4193.962960 #進程實際累積運行物理時間, ms
se.nr_migrations : 1303
nr_switches : 12433
nr_voluntary_switches : 11709
nr_involuntary_switches : 724
se.load.weight : 1048576
se.avg.load_sum : 116
se.avg.runnable_sum : 118784
se.avg.util_sum : 118784
se.avg.load_avg : 0
se.avg.runnable_avg : 0
se.avg.util_avg : 0
se.avg.last_update_time : 269493417332736
se.avg.util_est.ewma : 12
se.avg.util_est.enqueued : 1
policy : 0
prio : 120
clock-delta : 9
mm->numa_scan_seq : 0
numa_pages_migrated : 0
numa_preferred_nid : -1
total_numa_faults : 0
current_node=0, numa_group_id=0
numa_faults node=0 task_private=0 task_shared=0 group_private=0 group_shared=0
我現在想寫個腳本,可以實時顯示指定進程累積運行物理時間(sum_exec_runtime)。
代碼
通過 python 代碼實現:
#!/usr/bin/env python3
import sys
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
vcpu_thread1 = sys.argv[1]
vcpu_thread2 = sys.argv[2]
keywords = "sum_exec_runtime"
time_interval = 1000
xtime = 0
xdata = []
ydata1, ydata2 = [], []
#獲取指定pid的sum_exec_runtime值
def read_sum_exec_runtime(pid,keyword):
runtime = 0
with open('/proc/'+str(pid)+'/sched') as procf:
for line in procf.readlines():
if keyword in line:
runtime = float((line.split(':')[1]).strip())
#print("pid:", pid, "runtime:", "%.2f" % runtime)
return runtime
#繪圖刷新函數
def animate(i):
global xtime
xtime += time_interval/1000
xdata.append(xtime)
ydata1.append(read_sum_exec_runtime(vcpu_thread1, keywords))
ydata2.append(read_sum_exec_runtime(vcpu_thread2, keywords))
plt.cla()
plt.title(keywords)
plt.xlabel("time(s)")
plt.ylabel("runtime(ms)")
plt.plot(xdata, ydata1, marker='x', label=vcpu_thread1)
plt.plot(xdata, ydata2, marker='o', label=vcpu_thread2)
plt.legend()
anim = FuncAnimation(plt.figure(), animate, frames=None, interval=time_interval)
#plt.show()
anim.save('runtime.gif', writer='imagemagick', fps=60)
測試
啓動一個 qemu 虛擬機,兩個 vcpu(兩個 VCPU 線程 id 分別是 241255,241266),然後跑上面的程序:
./runtime.py 241255 241266
結果如下圖所示(只測量了 100s 左右,在 qemu 虛擬機裏跑了兩個純耗 CPU 時間的任務),可以看到 vcpu 線程的 runtime 直線上升。
在虛擬機裏只跑一個 cpu 消耗性任務,其曲線如下:
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/0dIU3b1WJV_N57AeoKU4pw