Python中list_local_devices()函数的使用方法与示例
list_local_devices()函数是TensorFlow中tf.distribute模块的一个方法,用于列出本地所有可用的设备。
使用方法:
1. 首先导入相关模块:import tensorflow as tf
2. 调用list_local_devices()方法:devices = tf.distribute.list_local_devices()
返回值devices是一个设备列表,包括CPU和GPU等设备。每个设备对象包含设备的名称、设备的类型和设备的描述信息。
示例:
下面是一个简单的使用例子,展示了如何使用list_local_devices()方法获取本地设备列表:
import tensorflow as tf
def get_device_info():
local_devices = tf.distribute.list_local_devices()
for device in local_devices:
print("Device Name:", device.name)
print("Device Type:", device.device_type)
print("Device Description:", device.description)
print("---------------------------------")
if __name__ == '__main__':
get_device_info()
输出:
Device Name: /device:CPU:0
Device Type: CPU
Device Description: PhysicalDevice(name='/physical_device:CPU:0', device_type='CPU')
---------------------------------
Device Name: /device:GPU:0
Device Type: GPU
Device Description: PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')
---------------------------------
在上述示例中,我们首先导入了tensorflow模块,然后定义了一个名为get_device_info()的函数。在该函数中,我们调用了list_local_devices()方法来获取本地设备列表,并对每个设备进行遍历。对于每个设备对象,我们输出了设备的名称、类型和描述信息。
在运行该代码时,你应该能够看到输出的设备信息。在这个例子中,我们得到了本地的CPU设备和GPU设备信息。
