Last active
October 23, 2021 04:13
-
-
Save guillemborrell/2a11a258fbd9cfd8d8e0bc14eac83fa7 to your computer and use it in GitHub Desktop.
Percentiles of rolling windows in time series with Cython
Que conste que en mi máquina la versión de numpy tarda 24.9 ms.
Con pequeñas modificaciones a la función window_percentile:
@cython.boundscheck(False)
def window_percentile(np.ndarray[double, ndim=1] arr, int window, double perc):
# Create numpy array and set auxiliary array. This requires the GIL.
cdef int imax = arr.shape[0]
cdef np.double_t[:] buffer = <np.double_t [:imax]>malloc(imax * sizeof(double))
cdef double NAN = math.NAN
cdef int i, j, stride
with nogil, parallel():
for i in prange(imax, schedule='dynamic'):
stride = i-(window-1)
if i >= window - 1:
buffer[i] = atomic_percentile(&arr[stride], window, perc)
else:
buffer[i] = NAN
return np.asarray(buffer)
Lo bajo a 13.8 ms. Parte de la gracia de Cython es levantar el GIL y poder correr con varios cores.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Results:
Reference: http://stackoverflow.com/a/6811241