python實現(xiàn)監(jiān)控指定進程的cpu和內(nèi)存使用率
為了測試某個服務的穩(wěn)定性,通常需要在服務長時間運行的情況下,監(jiān)控其資源消耗情況,比如cpu和內(nèi)存使用
這里借助python的psutil這個包可以很方便的監(jiān)控指定進程號(PID)的cpu和內(nèi)存使用情況
代碼
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() # better set interval second to calculate like: ?p.cpu_percent(interval=0.5) ?? ??? ?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
- 根據(jù)pid號獲取進程實例,固定時間間隔查詢其cpu和內(nèi)存的使用百分比
- 將監(jiān)控數(shù)據(jù)寫入文件,一邊后續(xù)分析
- 必要的話,也可以額外統(tǒng)計整個機器的資源狀況
實例
使用命令
python process_monitor.py 25272
文件保存結(jié)果
繪制出曲線圖
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python?Flask實現(xiàn)快速構(gòu)建Web應用的方法詳解
Flask是一個輕量級的Web服務器網(wǎng)關(guān)接口(WSGI)web應用框架,本文將和大家一起詳細探討一下Python?Flask?Web服務,需要的小伙伴可以學習一下2023-06-06django 數(shù)據(jù)庫 get_or_create函數(shù)返回值是tuple的問題
這篇文章主要介紹了django 數(shù)據(jù)庫 get_or_create函數(shù)返回值是tuple的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05Python獲取暗黑破壞神3戰(zhàn)網(wǎng)前1000命位玩家的英雄技能統(tǒng)計
這篇文章主要介紹了Python獲取暗黑3戰(zhàn)網(wǎng)前1000命位玩家的英雄技能統(tǒng)計的方法,借助urllib2模塊以類似爬蟲的機制來實現(xiàn),需要的朋友可以參考下2016-07-07詳解Open Folder as PyCharm Project怎么添加的方法
這篇文章主要介紹了詳解Open Folder as PyCharm Project怎么添加的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-12-12python 根據(jù)csv表頭、列號讀取數(shù)據(jù)的實現(xiàn)
這篇文章主要介紹了python 根據(jù)csv表頭、列號讀取數(shù)據(jù)的實現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-05-05