对tensorflow和pytorch的gpu测试

对tensorflow和pytorch的gpu测试

    • 1 tensorflow
    • 2 pytorch
    • 3 其他测试方法
      • 3.1 cmd
      • 3.2 Xshell

1 tensorflow

不论是tensorflow1.14还是2.0以上的版本,都可以用通用的一句来检测gpu是否可行,如果结果是True,则证明可以使用gpu

tf.test.is_gpu_available()

参考代码
tensorflow的gpu测试,结果为True证明gpu可用

import tensorflow as tf
# tf14
a = tf.constant(5)
sess = tf.Session()
sess.run(tf.global_variables_initializer())  # 全局变量初始化器
print(sess.run(a))
print(tf.test.is_gpu_available())
# tf2
a = tf.constant(5)
b = tf.constant(6)
tf.print(a + b)
print(tf.test.is_gpu_available())

2 pytorch

pytorch的安装比tensorflow要复杂一些,gpu版本的pytorch需要直接用

conda install pytorch==1.8.0 torchvision==0.9.0

这个过程需要等待一段时间,测试gpu的核心代码也是一句

torch.cuda.is_available()

参考代码
pytorch的gpu测试,结果为True证明gpu可用

import torch
import time
from torch import autograd
print(torch.__version__)
print(torch.cuda.is_available())

# torch创建gpu设置两种方法:
# Expected one of cpu, cuda, xpu, mkldnn, opengl, opencl, ideep, hip, msnpu, xla
# 1
device = torch.device("cuda")
print(device)
print(torch.cuda.get_device_name(0))
# 2
num_gpu = 1
device = torch.device("cuda:0" if (torch.cuda.is_available() and num_gpu > 0) else "cpu")
print(device)
print(torch.cuda.get_device_name(0))

pytorch的一些有趣的运算操作,比较在cpu和gpu的运算时间多少

print(torch.randn(3, 3))
print(torch.randn(3, 3).cuda())
a = torch.randn(10000, 1000)
b = torch.randn(1000, 10000)
print(a)
print(b)

t0 = time.time()
c = torch.matmul(a, b)
t1 = time.time()
print(a.device, t1 - t0, c.norm(2))
# torch gpu实现2种方法:
# 1
a = a.to(device)
b = b.to(device)
# 2
# a = a.cuda()
# b = b.cuda()

t0 = time.time()
c = torch.matmul(a, b)
t2 = time.time()
print(a.device, t2 - t0, c.norm(2))

t0 = time.time()
c = torch.matmul(a, b)
t2 = time.time()
print(a.device, t2 - t0, c.norm(2))

运算结果
对tensorflow和pytorch的gpu测试_第1张图片

3 其他测试方法

核心方法就是激活对应版本的环境,然后输入python指令,切换到与python互动的界面,
如果是tensorflow相关环境,则输入

import tensorflow
tensorflow.test.is_gpu_available()

如果是pytorch相关环境,则输入

import torch
torch.cuda.is_available()

3.1 cmd

对tensorflow和pytorch的gpu测试_第2张图片
对tensorflow和pytorch的gpu测试_第3张图片
对tensorflow和pytorch的gpu测试_第4张图片

3.2 Xshell

对tensorflow和pytorch的gpu测试_第5张图片
对tensorflow和pytorch的gpu测试_第6张图片
对tensorflow和pytorch的gpu测试_第7张图片
感谢大家的关注和支持,希望我写的文章能够让你们有收获。
如有不足,还请各位多多指正!

你可能感兴趣的:(GPU测试,pytorch,tensorflow,深度学习)