Vectorize

In [ ]:
import numpy as np
a = np.random.uniform(size=10000)
b = np.random.uniform(size=10000)
%time c = a + b
In [ ]:
def add_vectors(first, second):
    a = np.empty(first.shape)
    for i in xrange(len(first)):
        a[i] = first[i] + second[i]
        
In [ ]:
%time c = add_vectors(a, b)

Don't write for-loops!

If you can't avoid it (writing your custom algorithms)

Use Cython

In [ ]:
%load_ext cythonmagic
In [ ]:
%%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
In [ ]:
%time c = add_vectors_fast(a, b)
In [ ]:
%%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
In [ ]:
%time c = add_vectors_fast2(a, b)
In [ ]: