TensorFlow GPU与CPU运行速度比较

测试TensorFlow采用GPU或CPU对于同一任务的运行速度测试。

第一次使用TensorFlow,第2个月使用python,不是CS行业。

  • 测试环境

软件环境:windows10,VScode,TensorFlow2.x(实际上代码是tf1.x版本)

硬件环境:E5-2667v3QS×2 对比 2080Ti(七彩虹OC),112G内存

  • 测试代码

原代码来自:https://blog.csdn.net/beyond9305/article/details/90450246

argv元组的参数0为使用GPU或CPU计算;argv元组的参数1为计算规模大小,建议最大不超过30000,否则可能会爆内存或显存

import sys
# 以下两行代码以使用tf1.x版本
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
# 需要datetime
from datetime import datetime
 
argv = ("gpu",30000) 
device_name = argv[0]  # Choose device from cmd line. Options: gpu or cpu
# device_name = "gpu"  
shape = (int(argv[1]), int(argv[1]))
if device_name == "gpu":
    device_name = "/gpu:0"
else:
    device_name = "/cpu:0"
 
with tf.device(device_name):
    random_matrix = tf.random_uniform(shape=shape, minval=0, maxval=1)
    dot_operation = tf.matmul(random_matrix, tf.transpose(random_matrix))
    sum_operation = tf.reduce_sum(dot_operation)
 
startTime = datetime.now()
with tf.Session(config=tf.ConfigProto(log_device_placement=True)) as session:
        result = session.run(sum_operation)
        print(result)
 
# It can be hard to see the results on the terminal with lots of output -- add some newlines to improve readability.
print("\n" * 5)
print("Shape:", shape, "Device:", device_name)
print("Time taken:", datetime.now() - startTime)
print("\n" * 5)
# 运行结果:
# CPU:
#  Shape: (30000, 30000) Device: /cpu:0
#  Time taken: 0:00:55.894182
# GPU:
#  Shape: (30000, 30000) Device: /gpu:0
#  Time taken: 0:00:07.981562

上述代码对于多核CPU运用率非常高,16核32线程接近100%占用。

  • 测试结果

双路E5 2667v3(2.9GHz共计16核32线程) 运行时长55.89s

七彩虹2080Ti OC 运行时长7.98s

 

你可能感兴趣的:(tensorflow,python,cpu,gpu)