码迷,mamicode.com
首页 > 其他好文 > 详细

深度学习入门——测试PyTorch和Tensorflow能正常使用GPU

时间:2020-03-02 20:32:33      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:ace   cpu   https   dom   oca   rtt   示例   red   ons   

1、测试PyTorch能正常使用GPU:

import torch
torch.cuda.is_available()

返回结果:

True

 

2、测试Tensorflow能正常使用GPU:

示例一:

tf.test.is_gpu_available()

返回结果:

True

示例二:

gpu_device_name = tf.test.gpu_device_name()
print(gpu_device_name)

返回结果:

/device:GPU:0

示例三:

import tensorflow as tf
with tf.device(/cpu:0):
    a = tf.constant([1,2,3],shape=[3],name=a)
    b = tf.constant([1,2,3],shape=[3],name=b)
with tf.device(/gpu:0):
    c = a + b
    print(c)

返回结果:

tf.Tensor([2 4 6], shape=(3,), dtype=int32)

示例四:

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
def performanceTest(device_name,size):
    with tf.device(device_name): #选择具体的哪一个设备
        W = tf.random_normal([size, size],name=W) #以随机产生数值的方式建立W矩阵
        X = tf.random_normal([size, size],name=X) #以随机产生数值的方式建立X矩阵
        mul = tf.matmul(W, X,name=mul)
        sum_result = tf.reduce_sum(mul,name=sum) #将mul矩阵里面的值加总

    startTime = time.time() #记录开始运行的时间
    tfconfig=tf.ConfigProto(log_device_placement=True) #代表显示设备的相关信息
    with tf.Session(config=tfconfig) as sess:
        result = sess.run(sum_result)
    takeTimes=time.time()  - startTime   
    print(device_name," size=",size,"Time:",takeTimes )
    return takeTimes #返回运行时间

g=performanceTest("/gpu:0",10000)
c=performanceTest("/cpu:0",10000)

返回结果:

Device mapping:
/job:localhost/replica:0/task:0/device:XLA_CPU:0 -> device: XLA_CPU device
/job:localhost/replica:0/task:0/device:GPU:0 -> device: 0, name: GeForce RTX 2070 SUPER, pci bus id: 0000:01:00.0, compute capability: 7.5
/job:localhost/replica:0/task:0/device:XLA_GPU:0 -> device: XLA_GPU device

/gpu:0  size= 10000 Time: 0.3135712146759033
Device mapping:
/job:localhost/replica:0/task:0/device:XLA_CPU:0 -> device: XLA_CPU device
/job:localhost/replica:0/task:0/device:GPU:0 -> device: 0, name: GeForce RTX 2070 SUPER, pci bus id: 0000:01:00.0, compute capability: 7.5
/job:localhost/replica:0/task:0/device:XLA_GPU:0 -> device: XLA_GPU device

/cpu:0  size= 10000 Time: 5.693259954452515

 

参考:

https://blog.csdn.net/weixin_41770169/article/details/91437100

https://blog.csdn.net/william_hehe/article/details/79615894

https://www.runoob.com/python/python-date-time.html

https://blog.csdn.net/weixin_41503009/article/details/86930657

https://clatterrr.com/archives/2362

https://blog.csdn.net/weixin_38410551/article/details/103631977

深度学习入门——测试PyTorch和Tensorflow能正常使用GPU

标签:ace   cpu   https   dom   oca   rtt   示例   red   ons   

原文地址:https://www.cnblogs.com/ratels/p/12397381.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!