怎么用python代码查看可用的gpu,然后指定可用的gpu运行

查看gpu

python 复制代码
import torch

# 检查CUDA是否可用
if torch.cuda.is_available():
    # 获取GPU设备数量
    device_count = torch.cuda.device_count()

    # 列出可用的GPU设备
    for i in range(device_count):
        print(f"GPU {i}: {torch.cuda.get_device_name(i)}")
else:
    print("CUDA is not available. No GPU devices found.")

输出结果

设置指定gpu运行

指定上面输出的5号卡

python 复制代码
if torch.cuda.is_available():
    # 指定要使用的GPU设备编号
    device = torch.device("cuda:5")
    print(f"Using GPU {device} - {torch.cuda.get_device_name(device)}")
else:
    print("CUDA is not available. No GPU devices found.")

查看gpu的内存情况等

python 复制代码
import subprocess

# 执行nvidia-smi命令以获取GPU信息
nvidia_smi_output = subprocess.check_output("nvidia-smi", shell=True).decode()

# 切分输出为每个GPU的信息
gpu_info = nvidia_smi_output.strip().split('\n\n')

# 遍历每个GPU的信息
for i, info in enumerate(gpu_info):
    print(f"GPU {i}:")
    print(info)
相关推荐
用户8356290780514 小时前
无需 Office:Python 批量转换 PPT 为图片
后端·python
用户1474853079744 小时前
AI-动手深度学习环境搭建-d2l
深度学习
markfeng85 小时前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi6 小时前
Chapter 2 - Python中的变量和简单的数据类型
python
JordanHaidee6 小时前
Python 中 `if x:` 到底在判断什么?
后端·python
OpenBayes贝式计算6 小时前
解决视频模型痛点,TurboDiffusion 高效视频扩散生成系统;Google Streetview 涵盖多个国家的街景图像数据集
人工智能·深度学习·机器学习
ServBay6 小时前
10分钟彻底终结冗长代码,Python f-string 让你重获编程自由
后端·python
OpenBayes贝式计算6 小时前
OCR教程汇总丨DeepSeek/百度飞桨/华中科大等开源创新技术,实现OCR高精度、本地化部署
人工智能·深度学习·机器学习
闲云一鹤7 小时前
Python 入门(二)- 使用 FastAPI 快速生成后端 API 接口
python·fastapi
Rockbean8 小时前
用40行代码搭建自己的无服务器OCR
服务器·python·deepseek