只要配置好了GPU的驱动和cuda 以及cudnn等工具(配置好环境),程序执行会默认先使用GPU的,如果不能执行的话再使用CPU。有些配置好cuda的机器能够执行tensorflow,但是运行慢,可能是因为运行使用的是CPU运行,而不是GPU在执行程序,如何判断我们的程序是使用CPU还是GPU在执行TensorFlow。
可使用下面小程序测试:(参考:TensorFlow实战Google深度学习框架;郑泽宇)
import tensorflow as tf
a = tf.constant([1.2,2.3,3.6], shape=[3],name='a')
b = tf.constant([1.2,2.3,3.6], shape=[3],name='b')
c = a+b
session = tf.Session(config=tf.ConfigProto(log_device_placement=True))
print(session.run(c))
如果是GPU运行,则输入以下类似输出,会显示有GPU的输出:
Device mapping:
/job:localhost/replica:0/task:0/gpu:0 -> device: 0, name: Quadro M5000, pci bus id: 0000:01:00.0
add: (Add): /job:localhost/replica:0/task:0/gpu:0
b: (Const): /job:localhost/replica:0/task:0/gpu:0
a: (Const): /job:localhost/replica:0/task:0/gpu:0
[2.4 4.6 7.2]
如果是CPU运行则输入一下类似输出,不论你有几个核,都是CPU:0:
add: (Add): /job:localhost/replica:0/task:0/device:CPU:0
a: (Const): /job:localhost/replica:0/task:0/device:CPU:0
b: (Const): /job:localhost/replica:0/task:0/device:CPU:0
[2.4 4.6 7.2]