1. 程式人生 > 其它 >CPU與CUDA(GPU)的計算能力對比之一: Tensorflow矩陣乘

CPU與CUDA(GPU)的計算能力對比之一: Tensorflow矩陣乘

技術標籤:tensorflow人工智慧python

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!