利用Python的list_local_devices()方法列出本地设备的厂商
发布时间:2023-12-17 17:09:36
list_local_devices()是PyTorch的一个函数,用于列出本地设备的厂商信息。本地设备可以是CPU或GPU。该函数主要用于检查PyTorch是否能够使用GPU进行加速计算。
以下是使用Python的list_local_devices()方法列出本地设备厂商的示例代码:
import torch
def print_local_devices():
devices = torch.cuda.list_local_devices()
if len(devices) > 0:
print("Found {} GPU(s):".format(len(devices)))
for device in devices:
print(" - GPU: {}".format(device.name))
print(" Manufacturer: {}".format(device.vendor))
else:
print("No GPU found. Using CPU for computations.")
print_local_devices()
上述示例首先导入了torch模块,然后定义了一个名为print_local_devices()的函数。该函数使用torch.cuda.list_local_devices()方法获取本地设备列表,并进行相关输出。
在函数中,我们检查是否找到了GPU设备。如果我们找到了一个或多个GPU设备,则会显示找到了几个GPU,并打印每个GPU的名称和制造商。如果没有找到GPU设备,则会显示未找到GPU,并将使用CPU进行计算。
要运行上述代码,需要确保已经安装PyTorch和支持GPU计算的驱动程序。如果没有GPU设备,代码也会继续运行,并显示未找到任何GPU设备。
请注意,在某些情况下,可能需要在代码之前执行以下操作,以确保torch模块能够正确地找到GPU设备:
import os os.environ["CUDA_VISIBLE_DEVICES"] = "0"
这将设置环境变量CUDA_VISIBLE_DEVICES,指定可见的GPU设备索引。上述示例中的"0"表示 个GPU设备。如果有多个GPU,可以更改为其他索引号,或者使用逗号分隔的索引列表,如"0,1,2"。
通过使用Python的list_local_devices()方法,我们可以方便地检查本地设备的制造商,并根据需求选择合适的设备进行计算加速。
