import numpy as np
a = np.random.uniform(size=10000)
b = np.random.uniform(size=10000)
%time c = a + b
def add_vectors(first, second):
a = np.empty(first.shape)
for i in xrange(len(first)):
a[i] = first[i] + second[i]
%time c = add_vectors(a, b)
If you can't avoid it (writing your custom algorithms) Use Cython ===========
%load_ext cythonmagic
%%cython
import numpy as np
cimport numpy as np
def add_vectors_fast(first, second):
a = np.empty(first.shape)
for i in xrange(len(first)):
a[i] = first[i] + second[i]
return a
%time c = add_vectors_fast(a, b)
%%cython
cimport cython
cimport numpy as np
#@cython.boundscheck(False)
#@cython.wraparound(False)
def add_vectors_fast2(double[:] first, double[:] second):
cdef np.ndarray[double, ndim = 1, mode = "c"] a = np.ndarray(first.shape[0])
#cdef int i
for i in range(len(first)):
a[i] = first[i] + second[i]
return a
%time c = add_vectors_fast2(a, b)