python - 用cupy增加内环距离函数
问题描述
我试图在迭代内部循环数组时提高给定距离函数的计算速度 - c(x, y)。我试图使用带有随机值的 cupy 和基准测试。到目前为止,我有以下代码:
import time
import contextlib
import cupy as cp
import numpy as np
squared_diff = cp.ElementwiseKernel(
'float64 x, float64 y',
'float64 z',
'z = (x - y) * (x - y)',
'squared_diff')
x, y = np.random.randn(1000), np.random.randn(1000)
x_gpu, y_gpu = cp.random.randn(1000), cp.random.randn(1000)
c = np.zeros((len(x), len(y)))
c_gpu = cp.zeros((len(x), len(y)))
@contextlib.contextmanager
def timer(message):
cp.cuda.Stream.null.synchronize()
start = time.time()
yield
cp.cuda.Stream.null.synchronize()
end = time.time()
print('%s: %f sec' % (message, end - start))
with timer(' CPU '):
for i in range(len(x)):
for j in range(len(y)):
c[i, j] = (x[i] - y[i]) ** 2
with timer(' GPU '):
for i in range(len(x)):
for j in range(len(y)):
c_gpu[i, j] = squared_diff(x_gpu[i], y_gpu[j])
但是,与 CPU 相比,GPU 时间似乎要高得多。
CPU : 0.486763 sec
GPU : 26.627597 sec
在考虑使用 CUDA 提高计算速度背后的理论时,我是否缺少任何重要的提示或问题?
解决方案
您需要广播输入数组以使其进行元素计算。
def bcast(x, y, xp):
return (xp.broadcast_to(x[:, None], (1000, 1000)),
xp.broadcast_to(y, (1000, 1000)))
x, y = bcast(x, y, np)
with timer(' CPU '):
c = (x - y) ** 2
x_gpu, y_gpu = bcast(x_gpu, y_gpu, cp)
with timer(' GPU '):
c_gpu2 = squared_diff(x_gpu, y_gpu)
推荐阅读
- mysql - MySQL“无法创建测试文件”,“无法设置数据目录或目录”,无法使用初始密码连接
- php - 清理多行 Word 插入的中断
- r - 来自 autoxgboost 模型的特征重要性
- gulp - Gulp 缩小和移动具有相同文件夹结构的文件
- java - 使用 Java.exec() 执行 mv 命令;
- ios - addArrangedSubview 是重叠视图
- javascript - Mocha - 如何使用 before 块设置变量?
- git - 如何在 git 中创建提交模板
- node.js - 为什么我的函数在 storage.single 中被调用两次?
- c++ - c++如何正确重载+运算符