爲了測試某個服務的穩定性,通常需要在服務長時間運行的情況下,監控其資源消耗情況,比如cpu和內存使用
這裏藉助python的psutil這個包可以很方便的監控指定進程號(PID)的cpu和內存使用情況
代碼
process_monitor.py
import sys
import time
import psutil
# get pid from args
if len(sys.argv) < 2:
print ("missing pid arg")
sys.exit()
# get process
pid = int(sys.argv[1])
p = psutil.Process(pid)
# monitor process and write data to file
interval = 3 # polling seconds
with open("process_monitor_" + p.name() + '_' + str(pid) + ".csv", "a+") as f:
f.write("time,cpu%,mem%\n") # titles
while True:
current_time = time.strftime('%Y%m%d-%H%M%S',time.localtime(time.time()))
cpu_percent = p.cpu_percent()
mem_percent = p.memory_percent()
line = current_time + ',' + str(cpu_percent) + ',' + str(mem_percent)
print (line)
f.write(line + "\n")
time.sleep(interval)
- 支持跨平臺linux,windows,mac
- 根據pid號獲取進程實例,固定時間間隔查詢其cpu和內存的使用百分比
- 將監控數據寫入文件,一邊後續分析
- 必要的話,也可以額外統計整個機器的資源狀況
實例
使用命令
python process_monitor.py 25272
文件保存結果
繪製出曲線圖