Python中使用list_local_devices()函数查看TensorFlow的本地设备信息
发布时间:2023-12-24 18:00:13
在TensorFlow中,可以使用tf.config.experimental.list_local_devices()函数来获取当前机器上的本地设备列表及其相关信息。该函数返回一个列表,列表中的每个元素表示一个本地设备,并提供了设备的详细信息,如设备名称、设备类型、设备物理地址等。
以下是一个使用list_local_devices()函数的例子:
import tensorflow as tf
# 获取本地设备列表
devices = tf.config.experimental.list_local_devices()
# 遍历设备列表并输出设备信息
for device in devices:
print('Device name:', device.name)
print('Device type:', device.device_type)
if device.device_type == 'GPU':
print('Device index:', device.gpu_index)
print('')
运行上述代码,你会得到类似下面的输出:
Device name: /physical_device:CPU:0 Device type: CPU Device name: /physical_device:GPU:0 Device type: GPU Device index: 0
在这个例子中,list_local_devices()函数返回了两个本地设备:一个CPU设备(/physical_device:CPU:0)和一个GPU设备(/physical_device:GPU:0)。我们通过遍历设备列表,分别输出了设备的名称和类型。对于GPU设备,我们还输出了设备的索引。
使用list_local_devices()函数可以帮助我们了解当前机器上的可用设备,特别是在使用多个GPU进行并行计算时十分有用。我们可以根据设备的类型和索引选择要在哪个设备上执行特定的TensorFlow操作。
