【发布时间】:2020-08-04 12:36:29
【问题描述】:
我正在尝试如何使用 cupy 在 gpus 上进行有效计算。
在我的特定应用程序中,timeit 的执行时间取决于运行次数(当然)。然而不是线性的,而是线性的,首先是小斜率,然后是大斜率。你自己看: Bi-linear increase of execution time with number of executions
我的问题是:为什么会这样?
我对 GPU 计算或数字内部结构不是很有经验。我只是觉得这会是一个有趣的问题。
这是我如何测量时间的代码
import cupy as cp
n = 401
s = 100
p = 100
x = cp.linspace(-5, 5, n, dtype=cp.float32)[:, cp.newaxis].repeat(s, 1)
sig = cp.random.uniform(.2, .4, (s, p), dtype=cp.float32)
a = cp.random.uniform(1, 2, (s, p), dtype=cp.float32)
c = cp.random.uniform(-3, 3, (s, p), dtype=cp.float32)
def cp_g(x, a, c, s):
return cp.sum(cp.multiply(cp.exp(-cp.square(((x[...,cp.newaxis] - c) / s))), a * s / cp.sqrt(cp.float32(cp.pi))),axis=-1)
for i in cp.arange(10,1000,10):
timeit('y= cp_g(x,a,c,sig)', globals=globals(), number=int(i))
P.S.:如果有趣的话,我使用的硬件是 GeForce 1660 Super。库达 10.2。 Python 3.7.0(v3.7.0:1bf9cc5093,2018 年 6 月 27 日,04:59:51)[MSC v.1914 64 位 (AMD64)]
【问题讨论】:
-
这是因为您没有考虑 GPU 时间。为此,您应该同步设备:
timeit('y= cp_g(x,a,c,sig); cp.cuda.Device().synchronize()', ...)。会产生一点开销,但它会添加到所有运行中,因此运行之间的比较仍然是公平的。