以下是一个使用 Python 获取某个进程和系统 GPU 占用率,并将数据导入 CSV 文件的脚本示例:\n\npython\nimport psutil\nimport csv\nimport time\nimport GPUtil\n\n# 获取GPU占用率\ndef get_gpu_usage():\n gpus = GPUtil.getGPUs()\n gpu_usage = []\n for gpu in gpus:\n gpu_usage.append(gpu.load * 100)\n return gpu_usage\n\n# 获取指定进程的CPU占用率\ndef get_process_cpu_usage(process_name):\n for proc in psutil.process_iter(['pid', 'name', 'cpu_percent']):\n if proc.info['name'] == process_name:\n return proc.info['cpu_percent']\n return 0\n\n# 导入数据到CSV文件\ndef export_to_csv(data):\n with open('gpu_usage.csv', 'a', newline='') as file:\n writer = csv.writer(file)\n writer.writerow(data)\n\n# 主程序\nif __name__ == '__main__':\n process_name = 'your_process_name' # 替换为你要监测的进程名\n interval = 1 # 数据采集间隔,单位为秒\n\n while True:\n gpu_usage = get_gpu_usage()\n process_cpu_usage = get_process_cpu_usage(process_name)\n timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())\n\n data = [timestamp] + gpu_usage + [process_cpu_usage]\n export_to_csv(data)\n\n time.sleep(interval)\n\n\n请将your_process_name替换为你要监测的进程名,并确保已经安装了psutilgputil库。运行脚本后,它将每隔指定的时间间隔采集一次数据,并将数据以时间戳、各个GPU占用率和指定进程的CPU占用率的形式保存到gpu_usage.csv文件中。


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

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