在Python中使用TensorFlow库list_local_devices()函数列出可用的本地设备列表
发布时间:2024-01-12 06:30:35
在Python中,我们可以使用TensorFlow库的list_local_devices()函数来列出可用的本地设备列表。该函数返回一个设备列表,其中包含了所有可用的本地设备,如CPU、GPU等。
下面是一个使用list_local_devices()函数的例子:
import tensorflow as tf
# 列出本地设备列表
def list_devices():
devices = tf.config.list_local_devices()
for device in devices:
print(device.name, device.device_type)
# 调用函数
list_devices()
在这个例子中,我们导入了TensorFlow库,并定义了一个list_devices()函数来列出本地设备列表。在函数体中,我们使用tf.config.list_local_devices()函数来获取设备列表,并通过循环遍历每个设备。
在循环中,我们使用device.name和device.device_type属性来获取设备的名称和设备类型。然后,我们使用print()函数将设备名称和设备类型打印出来。
最后,我们调用list_devices()函数来列出可用的本地设备列表。
运行上述代码,将会输出类似下面的结果:
/device:CPU:0 CPU /device:GPU:0 GPU
这表示我们的机器上有一个CPU设备和一个GPU设备。根据输出结果,我们可以了解到当前机器上可用的本地设备类型和名称。
这就是使用TensorFlow库的list_local_devices()函数列出可用的本地设备列表的方法,并附上了一个使用例子。希望对你有所帮助!
