【发布时间】:2021-06-29 19:16:29
【问题描述】:
我是 Python 新手,我需要加速这个简单的代码。
我在 Matlab 中创建了这段代码,它“立即”运行。 我试图在 Python 中“转换”它,但它非常慢......
在我的最终代码中,这个片段操作必须循环一千次...... 所以最后,代码的这个特定部分需要尽可能高效......
# a and B define the size of the data
a=9000
b=4000
c=np.ones((a,)) # not one in my code
d=np.random.rand(a,b) # not random in my code
res=np.zeros((b,1)) # pre-alloc
# here is the loop to be speed up !
tic = time.time()
for x in range(b):
res[x]=sum(c*d[:,x])
toc = time.time()
print(toc-tic)
只是为了让它更难......理论上,“a”可以大到“百万”......而“b”可以大到几十万...... 不好玩……
有什么建议吗?
非常感谢您的帮助!
比纳比克
【问题讨论】:
-
始终考虑标准操作(在这种情况下为向量矩阵乘积)。在这种情况下,它就像
res=np.dot(c,d).reshape(-1,1)一样简单,大约需要。 10 毫秒而不是 5 秒。 (快 5000 倍)
标签: python arrays performance for-loop large-data