Unnecessary cutting slowly?

Hi, I am using scientific computing using numpy + numba. I realized that adding a numpy array in place is very slow ... compared to matlab

here is the matlab code:

tic;
% A,B are 2-d matrices, ind may not be distinct
for ii=1:N 
    A(ind(ii),:) =  A(ind(ii),:) +  B(ii,:);
end
toc;

and here is the numpy code:

s = time.time()
# A,B are numpy.ndarray, ind may not be distinct
for k in xrange(N):
     A[ind[k],:] += B[k,:];
print time.time() - s

The result shows that numpy code is 10 times slower than matlab ... which confuses me a lot.

Also, when I pull the complement from the for loop and just compare the one-time matrix addition with numpy.add, numpy and matlab seem to be comparable in speed.

One of the factors that I know is that Matlab uses JIT for version> = 2012a to speed up the loop, but I tried numba for python code, but it still doesn't even speed up a bit. I think this is because numba didn't touch the numpy.add function at all, so performance doesn't change at all.

, Matlab , .

, numpy?

+4
2

Try

A[ind] += B[:N]

. - .

ind , np.add.at:

np.add.at(A, ind, B[:N])
+3

, . 1s 0s ind.

def bar(A,B,ind):
    K,M =B.shape
    N,M =A.shape
    I = np.zeros((N,K))
    I[ind,np.arange(K)] = 1
    return A+np.dot(I,B)

, K,M,N = 30,14,15, 3 . , K,M,N = 300,100,150, .

0

All Articles