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

在运行脚本时有时需要监控脚本中各模块 占用的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("监控已停止。")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值