Tensorflow CPU/GPU之间的张量流切换

Tensorflow CPU/GPU之间的张量流切换,tensorflow,Tensorflow,安装了tensorflow GPU(在微薄的NVIDIA GeForce 950上运行),我想比较一下CPU的性能 我正在运行tensorFlow MNIST教程代码,并注意到速度有了显著提高——无论如何估计是这样的(2天前我在批量大小为100的笔记本电脑i7上运行了CPU版本,而在批量大小为10的桌面GPU上运行了CPU版本)--在CPU和GPU之间切换…但我只注意到当我将GPU上的批处理大小从100降低到10时速度增加 现在我缺乏一个客观的衡量我所获得的东西的标准 有没有办法在CPU和GPU

安装了tensorflow GPU(在微薄的NVIDIA GeForce 950上运行),我想比较一下CPU的性能

我正在运行tensorFlow MNIST教程代码,并注意到速度有了显著提高——无论如何估计是这样的(2天前我在批量大小为100的笔记本电脑i7上运行了CPU版本,而在批量大小为10的桌面GPU上运行了CPU版本)--在CPU和GPU之间切换…但我只注意到当我将GPU上的批处理大小从100降低到10时速度增加

现在我缺乏一个客观的衡量我所获得的东西的标准

有没有办法在CPU和GPU张量流之间切换?

使GPU不可见

export CUDA_VISIBLE_DEVICES=""
恢复正常

unset CUDA_VISIBLE_DEVICES

尝试将tf.device设置为cpu:0

with tf.Session() as sess:
     with tf.device("/cpu:0"):

另一种选择是在两个虚拟环境中安装tensorflow的cpu版本和gpu版本,下面列出了如何在虚拟环境中安装tensorflow的详细说明;这样,您就可以在两个终端上运行相同的代码,一个使用CPU,另一个使用GPU。

相当长的时间过去了。Tensorflow的最新版本(至少从2.0开始)不需要在有gpu支持和没有gpu支持的情况下安装这两个版本,因此您可以启动两个独立的
jupyter notebook
实例。遵循@Yaroslav的建议:

# Check if the server/ instance is having GPU/ CPU from python code
import sys
import tensorflow as tf
from tensorflow.python.client import device_lib

# device_lib.list_local_devices()     ## this command list all the processing device GPU and CPU


device_name = [x.name for x in device_lib.list_local_devices() if x.device_type == 'GPU']
if device_name[0] == "/device:GPU:0":
    device_name = "/gpu:0"
    #print('GPU')
else:
    #print('CPU')
    device_name = "/cpu:0"

with tf.device(device_name):
    a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
    b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
    c = tf.matmul(a, b)
with tf.Session() as sess:
    print (sess.run(c))    
$ CUDA_VISIBLE_DEVICES="" jupyter-notebook &
$ jupyter-notebook &

然后,您将在浏览器中打开两个独立的jupyter客户端,通常为
http://localhost:8888/
http://localhost:8889/
,分别在不支持GPU和支持GPU的情况下运行相同的.ipynb笔记本电脑并测量性能差异。

要关闭GPU,只需将其添加到脚本顶部即可

import os
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"

(如果您想再次使用GPU,请将其注释掉)

将其放在何处?。或者在运行
python my_script.py
@Chaine之前,在终端中放置
CUDA_VISIBLE_DEVICES=“”python myscript.py