以下是一个使用Python获取某个进程和系统GPU占用率,并将数据导入CSV文件的脚本示例:

import psutil
import csv
import time
import GPUtil

# 获取GPU占用率
def get_gpu_usage():
    gpus = GPUtil.getGPUs()
    gpu_usage = []
    for gpu in gpus:
        gpu_usage.append(gpu.load * 100)
    return gpu_usage

# 获取指定进程的CPU占用率
def get_process_cpu_usage(process_name):
    for proc in psutil.process_iter(['pid', 'name', 'cpu_percent']):
        if proc.info['name'] == process_name:
            return proc.info['cpu_percent']
    return 0

# 导入数据到CSV文件
def export_to_csv(data):
    with open('gpu_usage.csv', 'a', newline='') as file:
        writer = csv.writer(file)
        writer.writerow(data)

# 主程序
if __name__ == '__main__':
    process_name = 'your_process_name'  # 替换为你要监测的进程名
    interval = 1  # 数据采集间隔,单位为秒

    while True:
        gpu_usage = get_gpu_usage()
        process_cpu_usage = get_process_cpu_usage(process_name)
        timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

        data = [timestamp] + gpu_usage + [process_cpu_usage]
        export_to_csv(data)

        time.sleep(interval)

请将your_process_name替换为你要监测的进程名,并确保已经安装了psutilgputil库。运行脚本后,它将每隔指定的时间间隔采集一次数据,并将数据以时间戳、各个GPU占用率和指定进程的CPU占用率的形式保存到gpu_usage.csv文件中

Python 获取某个进程和系统gpu占用率的并导入csv文件脚本

原文地址: https://www.cveoy.top/t/topic/h38R 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录