import sys
import os
import time
import psutil
from datetime import datetime
# print "Welcome,current system is",os.name," 3 seconds late start to get data..."
#time.sleep(1)
line_num = 1
pid = int(sys.argv[1])
proc = psutil.Process(pid)
print(proc.name())
# function of Get CPU State;
def getCPUstate(interval=1):
return ("CPU: " + str(proc.cpu_percent(interval)) + "%")
def getMemorystate():
phymem = psutil.virtual_memory()
line = "Memory: %5s%% %6s/%s" % (
phymem.percent,
str(int(phymem.used / 1024 / 1024)) + "M",
str(int(phymem.total / 1024 / 1024)) + "M"
)
return line
def getMemorystate2():
return (' Memory: ' + str(proc.memory_info().rss / 1024 / 1024) + 'MB')
file_name = str(datetime.now().strftime("%m-%d_%H:%M_"))+proc.name()+'.txt'
try:
f = open(file_name, 'w+')
#print(datetime.now().strftime("%m-%d_%H:%M_"))
while 1:
text = getCPUstate() + getMemorystate2()
print(text)
f.write(text+'\n')
except KeyboardInterrupt:
#print(datetime.now().strftime("%D-%M-%S"))
print(file_name)
f.close()
使用方式
python3 read_cpu_men.py pid
如:
python3 read_cpu_men.py 3485
运行结束按ctrl+c结束,文件会以时间加上指定pid程序名保存在当前目录
可以用以下方式画出图表
import matplotlib.pyplot as plt
import numpy as np
import re
a = []
b = []
pattern = re.compile('CPU: (\d+\.\d+)% Memory: (\d+)MB')
with open("06-07_16:17_cartographer_node.txt") as lines:
for line in lines:
line = line.strip()
list_ = pattern.findall(line)
a.append(float(list_[0][0]))
b.append(int(list_[0][1]))
x1 = np.array(a)
x2 = np.array(b)
y = range(len(a))
plt.title(r'cartographer_node',fontsize=18)
l1, = plt.plot(y,x1,'g',label=r'CPU/%',lw=2)
l2, = plt.plot(y,x2,'r',label=r'Memory/MB',lw=2)
plt.legend(handles=[l1, l2], labels=['CPU/%', 'Memory/MB'], loc='best')
plt.show()
使用方式,修改代码中打开的文件路径为自己刚刚保存的文件路径
python3 show.py
显示如下图