%load_ext cythonmagic
%%cython
cimport numpy as cnp
import numpy as np
ctypedef cnp.float64_t FLOAT_t
cpdef FLOAT_t cython_sum(cnp.ndarray[FLOAT_t, ndim=1] A):
cdef double [:] x = A
cdef double sum = 0
cdef unsigned int N = A.shape[0]
for i in xrange(N):
sum += x[i]
return sum
cpdef FLOAT_t cython_avg(cnp.ndarray[FLOAT_t, ndim=1] A):
cdef double [:] x = A
cdef double sum = 0
cdef unsigned int N = A.shape[0]
for i in xrange(N):
sum += x[i]
return sum/N
cpdef FLOAT_t cython_silly_avg(cnp.ndarray[FLOAT_t, ndim=1] A):
cdef unsigned int N = A.shape[0]
return cython_avg(A)*N
A = np.random.random(100000)
%timeit A.mean()
10000 loops, best of 3: 143 µs per loop
%timeit cython_avg(A)
10000 loops, best of 3: 120 µs per loop
%timeit cython_sum(A)
10000 loops, best of 3: 119 µs per loop