C int is a native integer type whose width and representation depend on the C implementation. In Cython, declaring a parameter or local variable as int lets generated code use a C value rather than a general Python object. The Python-facing wrapper still handles the interface and its packing and unpacking. section 5.2.3
The performance difference appears in the generated implementation:
- An unannotated add-four function uses Python-object operations; its annotated counterpart accepts an int and performs the addition as a C expression. section 5.2.3
- Cython-level declarations are distinct from modern Python-level annotations. section 5.2.2
#cython: language_level=3
def add4(my_number):
i = my_number + 4
return i
def add4_annotated(int my_number):
cdef int i
i = my_number + 4
return i
Compare the unannotated and int-annotated add-four functions to see where Cython declarations change the implementation. section 5.2.3
Image-processing loop
An annotated Cython image-darkening implementation, including int loop dimensions, runs in about 1.5 seconds versus about 30 seconds for the native Python version. section 5.2.2
