CPU与CUDA(GPU)的计算能力对比之一: Tensorflow矩阵乘

CPU与CUDA(GPU)的计算能力对比之一: Tensorflow矩阵乘

结论:
1.Tensorflow 矩阵乘场景,CUDA 的效率是 CPU 的 1000 倍以上。
2. 测试过程中: GPU峰值占用率能够达到100%, CPU峰值占用率最高(观测到的)为51% , 大部分时间在20%以下。
3. 本测试不涉及 神经网络/深度学习/机器学习算法 , 仅为简单的矩阵乘(1亿 行元素 * 1 亿列元素)

环境概要:
CPU 9750 i7 ,32G 内存;
GPU Nvidia RTX2070 (8G显存)
Tensorflow 版本:2.3.1
CUDA 版本:10.1
cuDNN 版本:7.6.5

# 屏蔽tensorflow输出的log信息
# 注意:代码在import tensorflow之前
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"

import sys
print("python的版本信息:",sys.version)
#python的版本信息: 3.7.9 (default, Aug 31 2020, 17:10:11) [MSC v.1916 64 bit (AMD64)]

import tensorflow as tf

'''
验证GPU相对于CPU,在并行计算优势明显
'''
n=100000000 #1亿次  (2亿次 会发生内存分配OOM )
python的版本信息: 3.8.5 (default, Sep  3 2020, 21:29:08) [MSC v.1916 64 bit (AMD64)]
# 创建在CPU环境上运算的 2 个矩阵
with tf.device('/cpu:0'):
    cpu_a = tf.random.normal([1, n])
    cpu_b = tf.random.normal([n, 1])
    print(cpu_a.device, cpu_b.device) 
/job:localhost/replica:0/task:0/device:CPU:0 /job:localhost/replica:0/task:0/device:CPU:0
cpu_b.device
'/job:localhost/replica:0/task:0/device:CPU:0'
cpu_a.device
'/job:localhost/replica:0/task:0/device:CPU:0'
# 创建使用 GPU环境运算的 2 个矩阵
with tf.device('/gpu:0'):
    gpu_a = tf.random.normal([1, n])
    gpu_b = tf.random.normal([n, 1])
    print(gpu_a.device, gpu_b.device)
/job:localhost/replica:0/task:0/device:GPU:0 /job:localhost/replica:0/task:0/device:GPU:0
import timeit
def cpu_run(): # CPU 运算函数
    with tf.device('/cpu:0'):
        c = tf.matmul(cpu_a, cpu_b)
    return c
def gpu_run():# GPU 运算函数
    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('首先计算10次(含热身环境)的平均时间,CPU计算消耗时间:%.3fms,GPU计算消耗时间:%.3fms!'%(cpu_time*1000, gpu_time*1000) )  
首先计算10次(含热身环境)的平均时间,CPU计算消耗时间:732.556ms,GPU计算消耗时间:0.676ms!
#正式计算10次,取平均时间
cpu1_time = timeit.timeit(cpu_run, number=200)
gpu1_time = timeit.timeit(gpu_run, number=200)
print('正式计算200次的平均时间,CPU计算消耗时间:%.3fms,GPU计算消耗时间:%.3fms!'%(cpu1_time*1000, gpu1_time*1000))
正式计算200次的平均时间,CPU计算消耗时间:14245.693ms,GPU计算消耗时间:12.130ms!
  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值