Reputation: 13
I am new on cython and I need construct a list of the classes.
The class is:
cdef class Acl_cy:
cdef int s0
cdef str s1
cdef str s2
cdef str s3
cdef str s4
cdef int s5
cdef int s6
cdef str s7
cdef str s8
cdef str s9
cdef int s10
cdef str s11
cdef int s12
cdef int s13
If a create a list in python list_tmp = []
and appending the classes.
It will work but it will transform all cython classes in python object, because of this the code is slower.
Is it possible create a cython vector of the class, and use it on the for loop ?
Thanks
Upvotes: 1
Views: 1070
Reputation: 52246
cython extension classes are python objects, so there isn't any actual transformation going on, but your general sense is right that it could be adding indirection/overhead to the generated code.
The easiest thing you can is declare the type of the list elements you are accessing, this will generate somewhat more efficient attribute access - a full example is further below.
Outside of that, you could ditch python objects all together and use arrays of c-structs, vectors of c++-classes, etc.
%%cython
cdef class Acl_cy:
cdef public int s0, s1, s2
cdef public str st0, st1, st2
def __init__(self, s0, s1, s2, st0, st1, st2):
self.s0 = s0
self.s1 = s1
self.s2 = s2
self.st0 = st0
self.st1 = st1
self.st2 = st2
def make_list():
l = []
for _ in range(10000):
l.append(Acl_cy(1, 2, 3, 'a', 'b', 'c'))
return l
def loop():
cdef list l = make_list()
cdef int sum = 0
for itm in l:
sum += itm.s1
return sum
def loop_typed():
cdef list l = make_list()
cdef Acl_cy itm
cdef int sum = 0
for itm in l:
sum += itm.s1
return sum
# In [274]: %timeit loop()
# 1.35 ms ± 67.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
# In [275]: %timeit loop_typed()
# 808 µs ± 22.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Upvotes: 3