У меня есть этот фрагмент кода, показанный в последнем прямом эфире Siraj Raval:
%laod_ext Cython
%cython
#memory management helper for Cython
from cymem.cymem import Pool
#good old python
from random import random
#The cdef statement is used to declare C variables,types, and functions
cdef struct Rectangle:
#C variables
float w
float h
#the "*" is the pointer operator, it gives value stored at particular
address
#this saves memory and runs faster, since we don't have to duplicate the
data
cdef int check_rectangles_cy(Rectangle* rectangles, int n_rectangles, float
threshold):
cdef int n_out = 0
# C arrays contain no size information => we need to state it explicitly
for rectangle in rectangles[:n_rectangles]:
if rectangle.w * rectangle.h > threshold:
n_out += 1
return n_out
#python uses garbage collection instead of manual memory management
#which means developers can freely create objects
#and Python's memory manager will periodically look for any
# objects that are no longer referenced by their program
#this overhead makes demands on the runtime environment (slower)
# so manually memory management is better
def main_rectangles_fast():
cdef int n_rectangles = 10000000
cdef float threshold = 0.25
#The Poool Object will save memory addresses internally
#then free them when the object is garbage collected
cdef Pool mem = Pool()
cdef Rectangle* rectangles = <Rectangle*>mem.alloc(n_rectangles, sizeof(Rectangle))
for i in range(n_rectangles):
rectangles[i].w = random()
rectangles[i].h = random()
n_out = check_rectangles_cy(rectangles, n_rectangles, threshold)
print(n_out)
При запуске этот код выдает следующую ошибку:
File "ipython-input-18-25198e914011", 'line 9'
cdef struct Rectangle:
SyntaxError: invalid syntax
Что я написал не так?
Ссылка на видео: https://www.youtube.com/watch?v=giF8XoPTMFg