(深度学习)GPU比CPU慢?快看这里

GPU由于擅长矩阵运算,在深度学习尤其是计算机视觉方面得到了广泛的应用。

前几天在我废了好大劲在我的的电脑上安装了Tensorflow 2.0 - GPU,然后就迫不及待地去体验一下GPU的速度。

我去Tensorflow官网上直接复制了一段代码,就是最简单的神经网络识别MNIST手写数字数据集。然后分别用GPU和CPU跑了以下,结果让我大吃一惊。之前听别人说用GPU通常会比CPU快好几倍,而我经过尝试发现GPU竟然比CPU还要慢了好多!

经过请教别人和上网查资料得出结论:是因为模型规模过小,没有体现出GPU的优势。

下面先看一下我的电脑的CPU和GPU的配置:

硬件型号
CPU第六代英特尔酷睿i5-6200U处理器
GPUNVIDIA GeForce 940M

下面看代码。大家可以跑一下试试(不同硬件配置结果可能不同)

小规模神经网络模型(GPU比CPU慢)

#TensorFlow and tf.keras
import tensorflow as tf
#Helper libraries
import numpy as np
import matplotlib.pyplot as plt
from time import time

mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

#用CPU运算
startTime1 = time()

with tf.device('/cpu:0'):
    model = tf.keras.models.Sequential([
      tf.keras.layers.Flatten(input_shape=(28, 28)),
      tf.keras.layers.Dense(128, activation='relu'),
      tf.keras.layers.Dropout(0.2),
      tf.keras.layers.Dense(10, activation='softmax')
    ])
    model.compile(optimizer='adam',
                  loss='sparse_categorical_crossentropy',
                  metrics=['accuracy'])
    model.fit(x_train, y_train, epochs=10)
    model.evaluate(x_test, y_test)
t1 = time() - startTime1

#用GPU运算
startTime2 = time()

with tf.device('/gpu:0'):
    model = tf.keras.models.Sequential([
      tf.keras.layers.Flatten(input_shape=(28, 28)),
      tf.keras.layers.Dense(128, activation='relu'),
      tf.keras.layers.Dropout(0.2),
      tf.keras.layers.Dense(10, activation='softmax')
    ])
    model.compile(optimizer='adam',
                  loss='sparse_categorical_crossentropy',
                  metrics=['accuracy'])
    model.fit(x_train, y_train, epochs=10)
    model.evaluate(x_test, y_test)

t2 = time() - startTime2

#打印运行时间
print('使用cpu花的时间:', t1)
print('使用gpu花的时间:', t2)

结果:

使用cpu花的时间: 52.422937631607056
使用gpu花的时间: 122.77410888671875

GPU比CPU慢的原因大致为:
数据传输会有很大的开销,而GPU处理数据传输要比CPU慢,而GPU的专长矩阵计算在小规模神经网络中无法明显体现出来。

加深加宽隐藏层(GPU优势逐渐体现)

#TensorFlow and tf.keras
import tensorflow as tf
#Helper libraries
import numpy as np
import matplotlib.pyplot as plt
from time import time

mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

#CPU运行
startTime1 = time()

with tf.device('/cpu:0'):
    model = tf.keras.models.Sequential([
      tf.keras.layers.Flatten(input_shape=(28, 28)),
      tf.keras.layers.Dense(1000, activation='relu'),
      tf.keras.layers.Dropout(0.2),
      tf.keras.layers.Dense(1000, activation='relu'),
      tf.keras.layers.Dropout(0.2),
      tf.keras.layers.Dense(10, activation='softmax')
    ])
    model.compile(optimizer='adam',
                  loss='sparse_categorical_crossentropy',
                  metrics=['accuracy'])
    model.fit(x_train, y_train, epochs=10)
    model.evaluate(x_test, y_test)

t1 = time() - startTime1

#GPU运行
startTime2 = time()

with tf.device('/gpu:0'):
    model = tf.keras.models.Sequential([
      tf.keras.layers.Flatten(input_shape=(28, 28)),
      tf.keras.layers.Dense(1000, activation='relu'),
      tf.keras.layers.Dropout(0.2),
      tf.keras.layers.Dense(1000, activation='relu'),
      tf.keras.layers.Dropout(0.2),
      tf.keras.layers.Dense(10, activation='softmax')
    ])

    model.compile(optimizer='adam',
                  loss='sparse_categorical_crossentropy',
                  metrics=['accuracy'])
    
    model.fit(x_train, y_train, epochs=10)
    model.evaluate(x_test, y_test)

t2 = time() - startTime2

#打印运行时间
print('使用cpu花的时间:', t1)
print('使用gpu花的时间:', t2)

结果:

使用cpu花的时间: 390.03080129623413
使用gpu花的时间: 224.40780639648438

以上,希望能给大家带来帮助!

  • 36
    点赞
  • 77
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 8
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

本初-ben

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值