Skip to content

Instantly share code, notes, and snippets.

@HTLife
Created March 9, 2021 01:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HTLife/fbf072c5af66c9da6f39c52f94eeb542 to your computer and use it in GitHub Desktop.
Save HTLife/fbf072c5af66c9da6f39c52f94eeb542 to your computer and use it in GitHub Desktop.
# python3 plot.py 22760.csv
import matplotlib.pyplot as plt
import csv
import sys
x = []
y1 = []
y2 = []
with open(sys.argv[1],'r') as csvfile:
plots = csv.reader(csvfile, delimiter=',')
next(plots)
i = 0
startTime = 0
for row in plots:
if i==0:
startTime = float(row[0])
i+=1
x.append(float(row[0]) - startTime)
y1.append(float(row[3]))
y2.append(float(row[4]))
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
color = 'tab:red'
ax1.set_xlabel('Time(sec)')
ax1.set_ylabel('cpu(%)', color=color)
ax1.tick_params(axis='y', labelcolor=color)
ax1.plot(x,y1, color=color)
color = 'tab:blue'
ax2.set_ylabel('Memory(MB)', color=color)
ax2.tick_params(axis='y', labelcolor=color)
ax2.plot(x,y2)
fig.tight_layout()
plt.show()
#python3
# python3 main.py 22760
import os
import subprocess
import sys
import time
import psutil
def memory_usage_ps(pid):
import subprocess
out = subprocess.Popen(['ps', 'v', '-p', str(pid)],
stdout=subprocess.PIPE).communicate()[0].split(b'\n')
vsz_index = out[0].split().index(b'RSS')
mem = float(out[1].split()[vsz_index]) / 1024
return mem
if __name__ == "__main__":
pid = sys.argv[1]
print('monitoring pid ' + str(pid))
f = open(pid + ".csv", "w")
f.write('nowtime, totalCpu, totalMem, pidCpu, pidMem, pidName\n')
while True:
# totalCpu = subprocess.check_output('grep \'cpu \' /proc/stat | awk \'{usage=($2+$4)*100/($2+$4+$5)} END {print usage}\'', shell=True).rstrip()
# totalCpu = totalCpu.decode("utf-8")
totalCpu = psutil.cpu_percent(0.1)
vMem = psutil.virtual_memory()[2]
command='top -bn 1 -p ' + str(pid)
topResult = subprocess.check_output(command, shell=True).decode("utf-8")
lastLine = topResult.splitlines()[-1].split()
pidCpu = lastLine[-4]
# pidMem = lastLine[-3]
pidMem = memory_usage_ps(int(pid))
print(pidMem)
# pidName = lastLine[-1]
nowtime = "%.3f" % time.time()
summaryStr = '{},{},{},{},{}'.format(nowtime, totalCpu, vMem, pidCpu, pidMem)
f.write(summaryStr+'\n')
#print(summaryStr)
time.sleep(0.1)
f.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment