tensorflow 使用CPU和GPU,某度,某google一搜一大堆,排名靠前的都不一定對。如果你搜到我這篇,那麼你肯定準確了。
前提:你安裝了cuda等GPU環境沒有問題
1 、使用CPU
很多人會說,cpu啥都不用配置,直接用就是cpu,那是因爲你沒安裝好GPU的cuda驅動,如果安裝好了,默認tensorflow是使用CPU的而且,亂佔用。
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "" #這句關鍵
import time
import tensorflow as tf
with tf.device('/cpu:0'):
with tf.Session() as sess:
# Here 6 GBs of GPU RAM are allocated.
# time.sleep(10)
a = tf.constant([1,2,3,4],dtype=tf.float32)
a = tf.expand_dims(a,-1)
a_sum = tf.reduce_sum(a,1)
print(sess.run(a_sum))
2、使用GPU
主要要可控呀,配好用某一個GPU就用某一個GPU
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0" # 用GPU 0號卡
import time
import tensorflow as tf
with tf.device('/gpu:0'):
with tf.Session() as sess:
# Here 6 GBs of GPU RAM are allocated.
# time.sleep(10)
a = tf.constant([1,2,3,4],dtype=tf.float32)
a = tf.expand_dims(a,-1)
a_sum = tf.reduce_sum(a,1)
print(sess.run(a_sum))