TensorFlow使用GPU测试

查看当前TensorFlow版本

import tensorflow as tf
print(tf.__version__)

在这里插入图片描述

查看当前主机上运行的设备

import tensorflow as tf

gpus = tf.config.experimental.list_physical_devices(device_type='GPU')
cpus = tf.config.experimental.list_physical_devices(device_type='CPU')
print(gpus)
print(cpus)

在这里插入图片描述

查看GPU是否可用,指定在CPU/GPU上运行

import tensorflow as tf

# 指定在cpu上运行
with tf.device('/cpu:0'):
    cpu_a = tf.random.normal([10000, 1000])
    cpu_b = tf.random.normal([1000, 2000])
    cpu_c = tf.matmul(cpu_a, cpu_b)
print("cpu_a:", cpu_a.device)
print("cpu_b:", cpu_b.device)
print("cpu_c:", cpu_c.device)
# 查看gpu是否可用
print(tf.config.list_physical_devices('GPU'))
# 指定在gpu上运行
with tf.device('/gpu:0'):
    gpu_a = tf.random.normal([10000, 1000])
    gpu_b = tf.random.normal([1000, 2000])
    gpu_c = tf.matmul(gpu_a, gpu_b)
print("gpu_a:", gpu_a.device)
print("gpu_b:", gpu_b.device)
print("gpu_c:", gpu_c.device)

在这里插入图片描述

比较在CPU和GPU上的运行时间

import tensorflow as tf
import timeit


def cpu_run():
    with tf.device('/cpu:0'):
        cpu_a = tf.random.normal([10000, 1000])
        cpu_b = tf.random.normal([1000, 2000])
        c = tf.matmul(cpu_a, cpu_b)
    return c


def gpu_run():
    with tf.device('/gpu:0'):
        gpu_a = tf.random.normal([10000, 1000])
        gpu_b = tf.random.normal([1000, 2000])
        c = tf.matmul(gpu_a, gpu_b)
    return c


cpu_time = timeit.timeit(cpu_run, number=10)
gpu_time = timeit.timeit(gpu_run, number=10)
print("cpu:", cpu_time, "  gpu:", gpu_time)

在这里插入图片描述

  • 23
    点赞
  • 41
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值