使用gpu与cpu运行tensorflow 时间比较

使用gpu与cpu运行tensorflow 时间比较

import tensorflow as tf
import timeit

with tf.device('/cpu:0'):
    cpu_a =tf.random.normal([10000,1000])
    cpu_b =tf.random.normal([1000,2000])
    print(cpu_a.device,cpu_b.device)

with tf.device('/gpu:0'):
    gpu_a =tf.random.normal([10000,1000])
    gpu_b =tf.random.normal([1000,2000])
    print(gpu_a.device,gpu_b.device)

def cpu_run():
    with tf.device('/cpu:0'):
        c =tf.matmul(cpu_a,cpu_b)
    return c
def gpu_run():
    with tf.device('/gpu:0'):
        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('warmup time',cpu_time,gpu_time)

热身后运行时间
cpu_time=timeit.timeit(cpu_run,number=10)
gpu_time=timeit.timeit(gpu_run,number=10)
print('run time',cpu_time,gpu_time)

笔记本gtx2060运行结果如下:
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用GPU运行TensorFlow可以显著提高训练和推理的速度。以下是使用GPU运行TensorFlow的简单步骤: 1. 安装CUDA和cuDNN。这些是TensorFlowGPU运行所需的基本依赖项。您需要确保您的CUDA和cuDNN版本与您的TensorFlow版本兼容。您可以在TensorFlow官方文档中找到相应的版本兼容性信息。 2. 安装TensorFlow。您可以使用pip命令安装TensorFlow: ``` pip install tensorflow-gpu ``` 注意要安装与您的CUDA和cuDNN版本兼容的TensorFlow版本。 3. 编写TensorFlow代码。在代码中,您需要使用`tf.device`和`tf.config.experimental.list_physical_devices`指定GPU设备,并且使用`tf.config.experimental.set_memory_growth`启用动态内存增长。 ```python import tensorflow as tf # 检查GPU是否可用 if tf.test.is_gpu_available(): print('GPU可用') else: print('GPU不可用') # 指定GPU设备 device_name = '/device:GPU:0' # 启用动态内存增长 gpus = tf.config.experimental.list_physical_devices('GPU') if gpus: try: for gpu in gpus: tf.config.experimental.set_memory_growth(gpu, True) except RuntimeError as e: print(e) # 在GPU运行TensorFlow代码 with tf.device(device_name): # 编写TensorFlow代码 ``` 在上面的代码示例中,`device_name`变量指定要使用GPU设备,`tf.config.experimental.list_physical_devices`返回可用的GPU设备列表,`tf.config.experimental.set_memory_growth`启用动态内存增长。 4. 运行TensorFlow代码。在运行代码之前,确保您的CUDA和cuDNN已经正确安装,并且您的TensorFlow版本与您的CUDA和cuDNN版本兼容。如果一切顺利,您应该可以看到TensorFlow代码在GPU运行,并且速度比在CPU运行要快得多。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值