For example if I do this:
cdef np.ndarray[np.int64_t, ndim=1] my_array
Where is my my_array
stored? I would think that since I didn't tell cython to store in on the heap it would be stored on the stack, but after doing the following experiment it seems that it is stored on the heap, or somehow efficiently memory managed. How is memory managed with respect to my_array
? Maybe I am missing something obvious, but I couldn't find any documentation on it.
import numpy as np
cimport cython
cimport numpy as np
from libc.stdlib cimport malloc, free
def big_sum():
# freezes up:
# "a" is created on the stack
# space on the stack is limited, so it runs out
cdef int a[10000000]
for i in range(10000000):
a[i] = i
cdef int my_sum
my_sum = 0
for i in range(10000000):
my_sum += a[i]
return my_sum
def big_sum_malloc():
# runs fine:
# "a" is stored on the heap, no problem
cdef int *a
a = <int *>malloc(10000000*cython.sizeof(int))
for i in range(10000000):
a[i] = i
cdef int my_sum
my_sum = 0
for i in range(10000000):
my_sum += a[i]
with nogil:
free(a)
return my_sum
def big_numpy_array_sum():
# runs fine:
# I don't know what is going on here
# but given that the following code runs fine,
# it seems that entire array is NOT stored on the stack
cdef np.ndarray[np.int64_t, ndim=1] my_array
my_array = np.zeros(10000000, dtype=np.int64)
for i in range(10000000):
my_array[i] = i
cdef int my_sum
my_sum = 0
for i in range(10000000):
my_sum += my_array[i]
return my_sum