Functions

You can add type information to the arguments of a Python function by specifying the type in front of each of the argument names. Functions specified in this way will work and perform like regular Python functions, but their arguments will be type-checked. We can write a max_python function, which returns the greater value between two integers:

    def max_python(int a, int b):
return a if a > b else b

A function specified in this way will perform type-checking and treat the arguments as typed variables, just like in cdef definitions. However, the function will still be a Python function, and calling it multiple times will still need to switch back to the interpreter. To allow Cython for function call optimizations, we should declare the type of the return type using a cdef statement:

    cdef int max_cython(int a, int b): 
return a if a > b else b

Functions declared in this way are translated to native C functions and have much less overhead compared to Python functions. A substantial drawback is that they can't be used from Python, but only from Cython, and their scope is restricted to the same Cython file unless they're exposed in a definition file (refer to the Sharing declarations section).

Fortunately, Cython allows you to define functions that are both callable from Python and translatable to performant C functions. If you declare a function with a cpdef statement, Cython will generate two versions of the function: a Python version available to the interpreter, and a fast C function usable from Cython. The cpdef syntax is equivalent to cdef, shown as follows:

    cpdef int max_hybrid(int a, int b): 
return a if a > b else b

Sometimes, the call overhead can be a performance issue even with C functions, especially when the same function is called many times in a critical loop. When the function body is small, it is convenient to add the inline keyword in front of the function definition; the function call will be replaced by the function body itself. Our max function is a good candidate for inlining:

    cdef inline int max_inline(int a, int b): 
return a if a > b else b
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.151.220