我正在尝试计算两个大矩阵的内积。numpy
尝试计算点积时似乎会创建矩阵副本,这会导致我出现一些内存问题。谷歌搜索后,我发现numba
包裹很有希望。但是我不能让它正常工作。这是我的代码:
import numpy as np
from numba import jit
import time, contextlib
@contextlib.contextmanager
def timeit():
t=time.time()
yield
print(time.time()-t,"sec")
def dot1(a,b):
return np.dot(a,b)
@jit(nopython=True)
def dot2(a,b):
n = a.shape[0]
m = b.shape[1]
K = b.shape[0]
c = np.zeros((n,m))
for i in xrange(n):
for j in xrange(m):
for k in range(K):
c[i,j] += a[i,k]*b[k,j]
return c
def main():
a = np.random.random((200,1000))
b = np.random.random((1000,400))
with timeit():
c1 = dot1(a,b)
with timeit():
c2 = dot2(a,b)
具有以下运行时间:
dot1:
(0.034691810607910156, 'sec')
dot2:
(0.9215810298919678, 'sec')
谁能告诉我我在这里缺少什么?