liveBook · Manning

C int

As explained in Fast Python: High performance techniques for large datasets

A C int is a platform-specific integer type whose width and representation are defined by the C implementation and matched by language bindings for C interoperability.

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

How Fast Python: High performance techniques for large datasets covers it

How deep it goes
Traces declarations into generated C signatures and arithmetic, while deferring further optimization techniques.
Examples
Compares annotated and unannotated add-four functions and measures an annotated image loop against native Python.
What it assumes
Presents generated C as readable even without prior C knowledge.
What you can do after
Apply Cython C-level int declarations to parameters and loop variables to move operations from Python objects into generated C.
How it connects
Connects C int declarations to Cython, Python objects, and NumPy typed arrays.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Fast Python: High performance techniques for large datasets. The section links point to the parts of the book it draws on.