怎么用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)
相关推荐
职业码农NO.11 小时前
智能体推理范式: Plan-and-Execute(规划与执行)
人工智能·python·数据分析·系统架构·知识图谱·agent·集成学习
Aspect of twilight2 小时前
深度学习不同GPU性能比较
人工智能·深度学习
爱笑的眼睛112 小时前
超越`cross_val_score`:深入剖析Scikit-learn交叉验证API的设计哲学与高阶实践
java·人工智能·python·ai
丝瓜蛋汤2 小时前
chunking-free RAG简介
人工智能·深度学习·机器学习
STLearner2 小时前
VLDB 2025 | 时间序列(Time Series)论文总结(预测,异常检测,压缩,自动化等)
数据库·人工智能·深度学习·神经网络·机器学习·数据挖掘·时序数据库
Ven%3 小时前
【AI大模型算法工程师面试题解析与技术思考】
人工智能·python·算法
天勤量化大唯粉3 小时前
枢轴点反转策略在铜期货中的量化应用指南(附天勤量化代码)
ide·python·算法·机器学习·github·开源软件·程序员创富
AndrewHZ3 小时前
【复杂网络分析】什么是图神经网络?
人工智能·深度学习·神经网络·算法·图神经网络·复杂网络
Swizard3 小时前
拒绝“狗熊掰棒子”!用 EWC (Elastic Weight Consolidation) 彻底终结 AI 的灾难性遗忘
python·算法·ai·训练
Spider赵毅3 小时前
python实战 | 如何使用海外代理IP抓取Amazon黑五数据
python·tcp/ip·php