Commit 6e0a3823 authored by Robert Bradshaw's avatar Robert Bradshaw

Consolidate typing sections.

parent 1e359523
cdef functions
==============
Python function calls can be expensive--in Cython doubly so because
one might need to convert to and from Python objects to do the call.
In our example above, the argument is assumed to be a C double both inside f()
and in the call to it, yet a Python ``float`` object must be constructed around the
argument in order to pass it.
Therefore Cython provides a syntax for declaring a C-style function,
the cdef keyword::
cdef double f(double) except *:
return sin(x**2)
Some form of except-modifier should usually be added, otherwise Cython
will not be able to propagate exceptions raised in the function (or a
function it calls). Above ``except *`` is used which is always
safe. An except clause can be left out if the function returns a Python
object or if it is guaranteed that an exception will not be raised
within the function call.
A side-effect of cdef is that the function is no longer available from
Python-space, as Python wouldn't know how to call it. Using the
``cpdef`` keyword instead of cdef, a Python wrapper is also created,
so that the function is available both from Cython (fast, passing
typed values directly) and from Python (wrapping values in Python
objects).
Note also that it is no longer possible to change ``f`` at runtime.
Speedup: 45 times over pure Python.
.. figure:: htmlreport.png
Using the ``-a`` switch to the ``cython`` command line program (or
following a link from the Sage notebook) results in an HTML report
of Cython code interleaved with the generated C code. Lines are
colored according to the level of "typedness" -- white lines
translates to pure C without any Python API calls. This report
is invaluable when optimizing a function for speed.
Faster code by adding types Faster code via static typing
=========================== =============================
Cython is a Python compiler. This means that it can compile normal
Python code without changes (with a few obvious exceptions of some as-yet
unsupported language features). However, for performance critical
code, it is often helpful to add static type declarations, as they
will allow Cython to step out of the dynamic nature of the Python code
and generate simpler and faster C code - sometimes faster by orders of
magnitude.
It must be noted, however, that type declarations can make the source
code more verbose and thus less readable. It is therefore discouraged
to use them without good reason, such as where benchmarks prove
that they really make the code substantially faster in a performance
critical section. Typically a few types in the right spots go a long way.
All C types are available for type declarations: integer and floating
point types, complex numbers, structs, unions and pointer types.
Cython can automatically and correctly convert between the types on
assignment. This also includes Python's arbitrary size integer types,
where value overflows on conversion to a C type will raise a Python
``OverflowError`` at runtime. The generated C code will handle the
platform dependent sizes of C types correctly and safely in this case.
Types are declared via the cdef keyword.
Typing Variables
----------------
Consider the following pure Python code:: Consider the following pure Python code::
...@@ -42,3 +70,45 @@ difference, but in this case it is not much extra work to be ...@@ -42,3 +70,45 @@ difference, but in this case it is not much extra work to be
consistent and type the entire function. consistent and type the entire function.
This results in a 24 times speedup over the pure Python version. This results in a 24 times speedup over the pure Python version.
Typing Functions
----------------
Python function calls can be expensive--in Cython doubly so because
one might need to convert to and from Python objects to do the call.
In our example above, the argument is assumed to be a C double both inside f()
and in the call to it, yet a Python ``float`` object must be constructed around the
argument in order to pass it.
Therefore Cython provides a syntax for declaring a C-style function,
the cdef keyword::
cdef double f(double) except *:
return sin(x**2)
Some form of except-modifier should usually be added, otherwise Cython
will not be able to propagate exceptions raised in the function (or a
function it calls). Above ``except *`` is used which is always
safe. An except clause can be left out if the function returns a Python
object or if it is guaranteed that an exception will not be raised
within the function call.
A side-effect of cdef is that the function is no longer available from
Python-space, as Python wouldn't know how to call it. Using the
``cpdef`` keyword instead of cdef, a Python wrapper is also created,
so that the function is available both from Cython (fast, passing
typed values directly) and from Python (wrapping values in Python
objects).
Note also that it is no longer possible to change ``f`` at runtime.
Speedup: 45 times over pure Python.
.. figure:: htmlreport.png
Using the ``-a`` switch to the ``cython`` command line program (or
following a link from the Sage notebook) results in an HTML report
of Cython code interleaved with the generated C code. Lines are
colored according to the level of "typedness" -- white lines
translates to pure C without any Python API calls. This report
is invaluable when optimizing a function for speed.
Data types in Cython
====================
Cython is a Python compiler. This means that it can compile normal
Python code without changes (with a few obvious exceptions of some as-yet
unsupported language features). However, for performance critical
code, it is often helpful to add static type declarations, as they
will allow Cython to step out of the dynamic nature of the Python code
and generate simpler and faster C code - sometimes faster by orders of
magnitude.
It must be noted, however, that type declarations can make the source
code more verbose and thus less readable. It is therefore discouraged
to use them without good reason, such as where benchmarks prove
that they really make the code substantially faster in a performance
critical section. Typically a few types in the right spots go a long way.
All C types are available for type declarations: integer and floating
point types, complex numbers, structs, unions and pointer types.
Cython can automatically and correctly convert between the types on
assignment. This also includes Python's arbitrary size integer types,
where value overflows on conversion to a C type will raise a Python
``OverflowError`` at runtime. The generated C code will handle the
platform dependent sizes of C types correctly and safely in this case.
...@@ -17,7 +17,7 @@ CPython, as it is written in C. Other major implementations use Java ...@@ -17,7 +17,7 @@ CPython, as it is written in C. Other major implementations use Java
many external libraries that interface through the C language. It many external libraries that interface through the C language. It
has, however, remained non trivial to write the necessary glue code in has, however, remained non trivial to write the necessary glue code in
C, especially for programmers who are more fluent in a high-level C, especially for programmers who are more fluent in a high-level
language like Python than in a do-it-yourself language like C. language like Python than in a close-to-the-metal language like C.
Originally based on the well-known Pyrex [Pyrex]_, the Cython project has Originally based on the well-known Pyrex [Pyrex]_, the Cython project has
approached this problem by means of a source code compiler that approached this problem by means of a source code compiler that
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment