当前位置: 首页 > news >正文

(附代码)psutil实时监控脚本运行过程中消耗的资源

在运行脚本时有时需要监控脚本中各模块 占用的cpu以及memory的情况,一般是执行python xx.py后,另起temernal,输入top命令实时监控,但这个存在一个问题,当脚本运行时间比较久时,一直盯着屏幕 也不合适。

所以,可以在脚本中内置 资源监控代码,将实时资源变化记录到log文件,当脚本运行结束,监控也停止。

话不多说,下面是实际可用的代码:

import psutil
import threading
import os 
import timedef main()://自己的函数# 在主脚本开头启动监控线程monitor_thread = threading.Thread(target=monitor_resources, args=(), daemon=True)monitor_thread.start()'''下面补充自己的代码'''def monitor_resources(log_file="record_memory.log", interval=1):"""监控当前脚本的 CPU 核心数和内存使用情况,并将其记录到指定日志文件。:param log_file: 日志文件路径:param interval: 监控间隔(秒)"""process = psutil.Process(os.getpid())total_cores = psutil.cpu_count(logical=True)  # 获取总核心数with open(log_file, "w") as file:file.write("Timestamp, CPU %, Memory (GB)\n")try:while True:# 获取 CPU 使用率并转换为使用的核心数cpu_usage_percent = process.cpu_percent(interval=0)cpu_cores = (cpu_usage_percent / 100) * total_cores# 获取内存使用情况并转换为 GBmemory_usage_gb = process.memory_info().rss / (1024 ** 3)# 获取当前时间timestamp = time.strftime("%Y-%m-%d %H:%M:%S")# 记录数据file.write(f"{timestamp}, {cpu_cores:.2f}, {memory_usage_gb:.2f}\n")file.flush()  # 确保数据立即写入文件# 等待下次记录time.sleep(interval)except KeyboardInterrupt:print("监控已停止。")


http://www.mrgr.cn/news/37444.html

相关文章:

  • 如何选择高品质SD卡
  • 回溯九宫格质数c++
  • Therabody携手上海劳力士大师赛,全方位守护球员运动健康
  • 一文读懂Ingress-Nginx以及实践攻略
  • LeetCode[中等] 24.两两交换链表中的结点
  • CBC 模式安全问题
  • 【MATLAB代码】二维环境下的RSSI定位程序,自适应锚点数量,带图像输出、坐标输出、中文注释
  • 思想和认知,从身边的事情和从小经历就在培养。谁在起跑线!
  • 在 Windows8.1 下编译 Chromium (103.0.5060.68 之三)
  • 图文检索(3):On the Integration of Self-Attention and Convolution
  • 为什么电销要用外呼系统
  • Netty 与 WebSocket之间的关系
  • GAMIT使用wuhm产品解算北斗数据报错处理
  • Drivers on multiprocessor and multithreaded ASIC platforms (1)
  • 云打包p12苹果证书和profile文件在线制作流程
  • 【艾思科蓝】网络安全的隐秘战场:构筑数字世界的铜墙铁壁
  • Cisco Secure Firewall Management Center Virtual 7.6.0 发布下载,新增功能概览
  • 【前端样式】Sweetalert2简单用法
  • 用Python实现运筹学——Day 4: 线性规划的几何表示
  • Python中使用pip换源的详细指南