Python 获取系统和进程 GPU 占用率并写入 CSV 文件
要获取系统GPU占用率和某个进程的GPU占用率,可以使用NVIDIA的NVML库来实现。以下是一个示例代码,它获取系统GPU占用率和某个进程的GPU占用率,并将它们写入.csv文件:\n\npython\nimport csv\nimport time\nimport pynvml\n\n# 初始化NVML库\npynvml.nvmlInit()\n\n# 获取系统GPU数量\ndeviceCount = pynvml.nvmlDeviceGetCount()\n\n# 获取系统GPU占用率\ndef get_system_gpu_usage():\n gpu_usage = []\n for i in range(deviceCount):\n handle = pynvml.nvmlDeviceGetHandleByIndex(i)\n utilization = pynvml.nvmlDeviceGetUtilizationRates(handle)\n gpu_usage.append(utilization.gpu)\n return gpu_usage\n\n# 获取指定进程的GPU占用率\ndef get_process_gpu_usage(pid):\n gpu_usage = []\n for i in range(deviceCount):\n handle = pynvml.nvmlDeviceGetHandleByIndex(i)\n utilization = pynvml.nvmlDeviceGetComputeRunningProcesses(handle)\n for process in utilization:\n if process.pid == pid:\n gpu_usage.append(process.usedGpuMemory)\n return gpu_usage\n\n# 创建.csv文件并写入数据\ndef write_to_csv(system_gpu_usage, process_gpu_usage):\n with open('gpu_usage.csv', mode='w', newline='') as file:\n writer = csv.writer(file)\n writer.writerow(['System GPU Usage', 'Process GPU Usage'])\n for i in range(len(system_gpu_usage)):\n writer.writerow([system_gpu_usage[i], process_gpu_usage[i]])\n\n# 获取系统GPU占用率和指定进程的GPU占用率,并写入.csv文件\ndef monitor_gpu_usage(pid):\n while True:\n system_gpu_usage = get_system_gpu_usage()\n process_gpu_usage = get_process_gpu_usage(pid)\n write_to_csv(system_gpu_usage, process_gpu_usage)\n time.sleep(1)\n\n# 选择指定进程的PID\npid = 1234\n\n# 开始监控GPU占用率\nmonitor_gpu_usage(pid)\n\n# 关闭NVML库\npynvml.nvmlShutdown()\n\n\n请注意,你需要安装pynvml库来使用NVML库。你可以使用以下命令安装:\n\n\npip install pynvml\n\n\n在代码中,你需要将pid变量设置为你要监控的进程的PID。然后,运行代码将会不断地获取系统GPU占用率和指定进程的GPU占用率,并将它们写入名为gpu_usage.csv的.csv文件中。
原文地址: https://www.cveoy.top/t/topic/pNc7 著作权归作者所有。请勿转载和采集!