Get the App
SLTechnology News&Howtos  ›  Development  › 

How does python monitor the cpu and memory usage of a specified process

Shulou Source: shulou.com Published: 2022-06-02 04:08:48 09月19日 Update

This article introduces how python monitors the cpu and memory utilization of a specified process. The content is very detailed. Interested friends can use it for reference. I hope it will be helpful to you.

To test the stability of a service, you usually need to monitor its resource consumption, such as cpu and memory usage, when the service is running for a long time

Here, with the help of python's psutil package, you can easily monitor the cpu and memory usage of the specified process number (PID).

Code

Process_monitor.py

Import sysimport timeimport psutil# get pid from argsif len (sys.argv)

< 2: print ("missing pid arg") sys.exit()# get processpid = int(sys.argv[1])p = psutil.Process(pid)# monitor process and write data to fileinterval = 3 # polling secondswith 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 根据pid号获取进程实例,固定时间间隔查询其cpu和内存的使用百分比 将监控数据写入文件,一边后续分析 必要的话,也可以额外统计整个机器的资源状况 实例 使用命令 python process_monitor.py 25272 文件保存结果 绘制出曲线图

So much for sharing the cpu and memory usage of the specified process on how python monitors the specified process. I hope the above content can be helpful to you and learn more. If you think the article is good, you can share it for more people to see.

Tags: Memory monitoring process situation usage content instances files more resources help services good necessary code interests commands guys buddies data Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn Shulou Information OPPO Reno NVidia Xiaomi