构想
进程的调度数据可通过proc文件系统查看,/prod/${pid}/sched中的参数,对性能优化来说很有参考意义,比如1号进程的数据如下:
代码语言:javascript复制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代码实现:
代码语言:javascript复制#!/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消耗性任务,其曲线如下: