【问题标题】:Why my GPU piece of code run much slower then cpu为什么我的 GPU 代码运行速度比 cpu 慢得多
【发布时间】:2016-10-23 18:02:46
【问题描述】:

这是我们随处可见的标准示例代码之一...

import time
import numpy

import pycuda.gpuarray as gpuarray
import pycuda.cumath as cumath
import pycuda.autoinit

size = 1e7

t0 = time.time()
x = numpy.linspace(1, size, size).astype(numpy.float32)
y = numpy.sin(x)
t1 = time.time()

cpuTime = t1-t0
print(cpuTime)

t0 = time.time()
x_gpu = gpuarray.to_gpu(x)
y_gpu = cumath.sin(x_gpu)
y = y_gpu.get()
t1 = time.time()

gpuTime = t1-t0
print(gpuTime)

结果是:cpu 为 200 毫秒,GPU 为 2.45 秒...超过 10 倍

我正在运行 win 10... 与 PTVS 的 2015...

最好的问候...

斯蒂芬

【问题讨论】:

  • 首先,您可能应该使用timeit 来准确计算平均代码执行时间。其次,gpuarray.to_gpu(x) 调用中可能存在大量开销。尝试在计时功能之外进行此设置。最后,请记住,numpy 已针对此类操作进行了高度优化。因此,在没有优化 GPU 代码的情况下,在某些情况下看到 GPU 性能较差并非没有道理。
  • 我已经使用timeit 模块运行了上面的代码。对于 gpu 代码,我每循环 20.6 毫秒(100 个循环),对于 numpy cpu 代码,每循环 129 毫秒。 GPU=GTX760,CPU=i5-2400。有趣的是,gpu 代码第一次在交互式 python 提示符下运行时似乎运行速度较慢(400 毫秒),但在同一实例中重复执行时运行速度更快(20 毫秒)。
  • 谢谢...是的,我也看到了相同的...相当多的开销...第一次通过...

标签: python gpu pycuda


【解决方案1】:

看起来pycuda 在您第一次调用cumath.sin() 函数时引入了一些额外的开销(在我的系统上约为400 毫秒)。我怀疑这是因为需要为被调用的函数编译 CUDA 代码。更重要的是,这种开销与传递给函数的数组的大小无关。对 cumath.sin() 的额外调用要快得多,因为 CUDA 代码已经编译以供使用。在我的系统上,问题中给出的 gpu 代码运行时间约为 20 毫秒(重复运行),而 numpy 代码的运行时间约为 130 毫秒。

我自称对pycuda 的内部运作了解不多,因此很想听听其他人对此的看法。

【讨论】:

  • 非常感谢您的回答...是的,它似乎有很多开销...
猜你喜欢
  • 2022-01-19
  • 2012-08-17
  • 2015-09-23
  • 1970-01-01
  • 2015-12-27
  • 2011-08-27
  • 1970-01-01
  • 2019-07-10
相关资源
最近更新 更多