在运行脚本时有时需要监控脚本中各模块 占用的cpu以及memory的情况,一般是执行python xx.py后,另起temernal,输入top命令实时监控,但这个存在一个问题,当脚本运行时间比较久时,一直盯着屏幕 也不合适。
所以,可以在脚本中内置 资源监控代码,将实时资源变化记录到log文件,当脚本运行结束,监控也停止。
话不多说,下面是实际可用的代码:
import psutil
import threading
import os
import time
def 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
# 获取内存使用情况并转换为 GB
memory_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("监控已停止。")