python - 为什么我的 GPU 在矩阵运算中比 CPU 慢?

标签 python machine-learning deep-learning gpgpu cupy

CPU:i7-9750 @2.6GHz(带 16G DDR4 内存);显卡:英伟达Geforce GTX 1600 TI (6G);操作系统:Windows 10-64位

我试着看看 GPU 在做基本矩阵运算时与 CPU 相比有多快,我基本上遵循了这个 https://towardsdatascience.com/heres-how-to-use-cupy-to-make-numpy-700x-faster-4b920dda1f56 .以下是我 super 简单的代码

import numpy as np
import cupy as cp
import time

### Numpy and CPU
s = time.time()
A = np.random.random([10000,10000]); B = np.random.random([10000,10000])
CPU = np.matmul(A,B); CPU *= 5
e = time.time()
print(f'CPU time: {e - s: .2f}')

### CuPy and GPU
s = time.time()
C= cp.random.random([10000,10000]); D = cp.random.random([10000,10000])
GPU = cp.matmul(C,D); GPU *= 5
cp.cuda.Stream.null.synchronize()  
# to let the code finish executing on the GPU before calculating the time
e = time.time()
print(f'GPU time: {e - s: .2f}')

具有讽刺意味的是,它表明 CPU 时间:11.74 GPU 时间:12.56

这让我很困惑。在大型矩阵运算上,GPU 怎么可能比 CPU 还慢?请注意,我什至没有应用并行计算(我是初学者,我不确定系统是否会为我打开它。)我确实检查过类似的问题,例如Why is my CPU doing matrix operations faster than GPU instead?。 .但这里我使用的是 cupy 而不是 mxnet(cupy 较新,专为 GPU 计算而设计)。

有人可以帮忙吗?我真的很感激!

最佳答案

numpy random 默认生成 float (32 位)。 Cupy random 默认生成 64 位( double )。要进行同类比较,请像这样更改 GPU 随机数生成:

C= cp.random.random([10000,10000], dtype=cp.float32)
D = cp.random.random([10000,10000], dtype=cp.float32)

我的硬件(CPU 和 GPU)与您不同,但是一旦进行此更改,GPU 版本比 cpu 版本快大约 12 倍。使用 cupy 生成随机数的 ndarray,矩阵乘法和标量乘法总共不到一秒

关于python - 为什么我的 GPU 在矩阵运算中比 CPU 慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64409663/

相关文章:

python - 使用 np.vectorize 时出现 ValueError - 我哪里出错了?

python - 从一组给定的单词中造出一个有意义的句子

matlab - Matlab 中 K 均值聚类的聚类索引的重新排序

tensorflow - 序列元素打乱后的奇怪序列分类性能

machine-learning - 不同的学习率会影响batchnorm的设置。为什么?

python - openpyxl - 能够从图表中删除边框吗?

python - Gensim Word2Vec 'you must first build vocabulary before training the model'

deep-learning - HUGGINGFACE 类型错误 : '>' not supported between instances of 'NoneType' and 'int'

python - 更快地计算特殊相关距离矩阵

python - ValueError(u"无效模式,应为 'c' 或 'fortran' ,得到 f\x00o\x00r\x00t",)