1. 檢測(cè)方法
Session對(duì)象在使用完后需要關(guān)閉以釋放資源. 除了顯式調(diào)用 close 外, 也可以使用 "with" 代碼塊 來(lái)自動(dòng)完成關(guān)閉動(dòng)作.
同時(shí),在實(shí)現(xiàn)上, TensorFlow 將圖形定義轉(zhuǎn)換成分布式執(zhí)行的操作, 以充分利用可用的計(jì)算資源(如 CPU 或 GPU). 一般你不需要顯式指定使用 CPU 還是 GPU, TensorFlow 能自動(dòng)檢測(cè). 如果檢測(cè)到 GPU, TensorFlow 會(huì)盡可能地利用找到的第一個(gè) GPU 來(lái)執(zhí)行操作. 如果機(jī)器上有超過(guò)一個(gè)可用的 GPU, 除第一個(gè)外的其它 GPU 默認(rèn)是不參與計(jì)算的. 為了讓 TensorFlow 使用這些 GPU, 你必須將 op 明確指派給它們執(zhí)行.with...Device語(yǔ)句用來(lái)指派特定的 CPU 或 GPU 執(zhí)行操作. (tf.device("/gpu:1"):)
基于此, 寫(xiě)了兩個(gè)文件,testGPU1.py 和testGPU2.py?
這里重點(diǎn)介紹一下第一種:?
def get_available_gpus():
"""
code from http://stackoverflow.com/questions/38559755/how-to-get-current-available-gpus-in-tensorflow
"""
from tensorflow.python.client import device_lib as _device_lib
local_device_protos = _device_lib.list_local_devices()
return [x.name for x in local_device_protos if x.device_type == 'GPU']
get_available_gpus()