2 Jan 2012 15:46
Why is one function slower than the other, despite that "cimport numpy" is used?
Jieyun Fu <jieyunfu <at> gmail.com>
2012-01-02 14:46:49 GMT
2012-01-02 14:46:49 GMT
Hi all,
I am comparing the performance between these two short functions (I
understand both functions can be directly vectorized using
numpy.searchsorted, but I just wanted to compare them nonetheless),
and surprisingly g_cython() is significantly slower than
g_less_cython(). Why is that? I uses cimport numpy to allow cython to
index the data in array a and b more efficiently,so g_cython() should
definitely be faster?
I attach the source code and test cases below. Thanks!
def g_cython(np.ndarray[np.int_t, ndim = 1] a, percentile):
cdef int i
cdef int n = len(a)
cdef np.ndarray[np.int_t, ndim = 1] b = np.zeros(n)
for i in xrange(n):
b[i] = np.searchsorted(percentile, a[i])
return b
def g_less_cython(a, percentile):
cdef int i
b = np.zeros_like(a)
for i in xrange(len(a)):
b[i] = np.searchsorted(percentile, a[i])
return b
Test cases:
In [1]: import numpy as np
(Continue reading)
RSS Feed