为什么我的GPU在矩阵运算方面比CPU慢?

2024-04-27 04:00:54 发布

您现在位置:Python中文网/ 问答频道 /正文

CPU:i7-9750@2.6GHz(带16G DDR4 Ram);GPU:Nvidia Geforce GTX 1600钛(6G);操作系统:Windows 10-64位

我试着看看GPU做基本矩阵运算的速度比CPU快多少,我基本上遵循了这个https://towardsdatascience.com/heres-how-to-use-cupy-to-make-numpy-700x-faster-4b920dda1f56。下面是我的超级简单代码

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计算而设计的)

有人能帮忙吗?我真的很感激


Tags: andthetoimportnumpygputimeas
1条回答
网友
1楼 · 发布于 2024-04-27 04:00:54

numpy random正在生成浮点(32位)作为默认值。默认情况下,Cupy random生成64位(双精度)。要进行苹果对苹果的比较,请按如下方式更改GPU随机数生成:

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

我有不同的硬件(CPU和GPU)比你,但一旦这个变化是作出的GPU版本约12倍快于CPU版本。使用cupy生成随机数数组、矩阵乘法和标量乘法总共不到1秒

相关问题 更多 >