Cython tutorial: Hur man påskyndar Python

Python är ett kraftfullt programmeringsspråk som är lätt att lära sig och lätt att arbeta med, men det är inte alltid det snabbaste att köra - speciellt när du har att göra med matte eller statistik. Tredjepartsbibliotek som NumPy, som omsluter C-bibliotek, kan förbättra prestandan för vissa operationer avsevärt, men ibland behöver du bara råhastigheten och kraften hos C direkt i Python.

Cython har utvecklats för att göra det lättare att skriva C-tillägg för Python och för att möjliggöra att befintlig Python-kod förvandlas till C. Dessutom tillåter Cython att den optimerade koden levereras med en Python-applikation utan externa beroenden.

I den här handledningen går vi igenom stegen som behövs för att omvandla befintlig Python-kod till Cython och använda den i en produktionsapplikation.

Relaterad video: Använda Cython för att påskynda Python

Ett Cython-exempel

Låt oss börja med ett enkelt exempel från Cythons dokumentation, en inte särskilt effektiv implementering av en integrerad funktion:

def f (x):

    returnera x ** 2-x

def integrate_f (a, b, N):

    s = 0

    dx = (ba) / N

    för jag inom intervallet (N):

        s + = f (a + i * dx)

    returnera s * dx

Koden är lätt att läsa och förstå, men den går långsamt. Detta beror på att Python ständigt måste konvertera fram och tillbaka mellan sina egna objekttyper och maskinens råa numeriska typer.

Tänk nu på Cython-versionen av samma kod, med Cythons tillägg understrukna:

 cdef f (dubbel x):

    returnera x ** 2-x

def integrate_f (dubbel a, dubbel b, int N):

    cdef int i

    cdef dubbel s, x, dx

    s = 0

    dx = (ba) / N

    för jag inom intervallet (N):

        s + = f (a + i * dx)

    returnera s * dx

Dessa tillägg tillåter oss att uttryckligen deklarera variabeltyper genom hela koden, så att Cython-kompilatorn kan översätta de "dekorerade" tilläggen till C. 

Relaterad video: Hur Python gör programmeringen enklare

Perfekt för IT, förenklar Python många typer av arbete, från systemautomation till arbete i banbrytande fält som maskininlärning.

Cythonsyntax

Nyckelorden som används för att dekorera Cython-kod finns inte i konventionell Python-syntax. De utvecklades speciellt för Cython, så all kod som dekoreras med dem kommer inte att köras som ett konventionellt Python-program.

Dessa är de vanligaste elementen i Cythons syntax:

Variabla typer

Några av de variabeltyper som används i Cython är ekon av Pythons egna typer, såsom  int, floatoch long. Andra Cython-variabeltyper finns också i C, som chareller struct, liksom deklarationer som unsigned long. Och andra är unika för Cython, som binten C-nivårepresentation av Python- True/Falsevärden.

Den cdefoch cpdeffunktionstyper

Den cdefnyckelordet indikerar användningen av en Cython eller C-typ. Det används också för att definiera funktioner mycket som du skulle göra i Python.

Functions written in Cython using Python’s def keyword are visible to other Python code, but incur a performance penalty. Functions that use the cdef keyword are only visible to other Cython or C code, but execute much faster. If you have functions that are only called internally from within a Cython module, use cdef.

A third keyword, cpdef, provides compatibility with both Python code and C code, in such a way that C code can access the declared function at full speed. This convenience comes at a cost, though: cpdef functions generate more code and have slightly more call overhead than cdef.

Other Cython keywords

Other keywords in Cython provide control over aspects of program flow and behavior that isn’t available in Python:

  • gil and nogil. These are context managers used to delineate sections of code that require (with gil:) or do not require (with nogil:) Python’s Global Interpreter Lock, or GIL. C code that makes no calls to the Python API can run faster in a nogil block, especially if it is performing a long-running operation such as reading from a network connection.
  • cimportThis directs Cython to import C data types, functions, variables, and extension types. Cython apps that use NumPy’s native C modules, for instance, use cimport to gain access to those functions.
  • include. This places the source code of one Cython file inside another, in much the same way as in C. Note that Cython has a more sophisticated way to share declarations between Cython files other than just includes.
  • ctypedef. Used to refer to type definitions in external C header files.
  • extern. Used with cdef to refer to C functions or variables found in other modules.
  • public/api. Used to make declarations in Cython modules that will be visible to other C code.
  • inline. Used to indicate a given function should be inlined, or have its code placed in the body of the calling function whenever it is used, for the sake of speed. For instance, the f function in the above code example could be decorated with inline to reduce its function call overhead, because it is only used in one place. (Note that the C compiler might perform its own inlining automatically, but inline lets you specify explicitly if something should be inlined.)

It is not necessary to know all of the Cython keywords in advance. Cython code tends to be written incrementally—first you write valid Python code, then you add Cython decoration to speed it up. Thus you can pick up Cython’s extended keyword syntax piecemeal, as you need it.

Compile Cython

Now that we have some idea of what a simple Cython program looks like and why it looks the way it does, let’s walk through the steps needed to compile Cython into a working binary.

To build a working Cython program, we will need three things:

  1. The Python interpreter. Use the most recent release version, if you can.
  2. The Cython package. You can add Cython to Python by way of the pip package manager: pip install cython
  3. A C compiler.

Item #3 can be tricky if you’re using Microsoft Windows as your development platform. Unlike Linux, Windows doesn’t come with a C compiler as a standard component. To address this, grab a copy of Microsoft Visual Studio Community Edition, which includes Microsoft’s C compiler and costs nothing. 

Note that, as of this writing, the most recent release version of Cython is 0.29.16, but a beta version of Cython 3.0 is available for use. If you use pip install cython, the most current non-beta version will be installed. If you want to try out the beta, use pip install cython>=3.0a1 to install the most recent edition of the Cython 3.0 branch. Cython’s developers recommend trying the Cython 3.0 branch whenever possible, because in some cases it generates significantly faster code.

Cython programs use the .pyx file extension. In a new directory, create a file named num.pyx that contains the Cython code example shown above (the second code sample under “A Cython example”) and a file named main.py that contains the following code:

from num import integrate_f

print (integrate_f(1.0, 10.0, 2000))

This is a regular Python progam that will call the integrate_f function found in num.pyx. Python code “sees” Cython code as just another module, so you don’t need to do anything special other than import the compiled module and run its functions.

Finally, add a file named setup.py with the following code:

from distutils.core import setup from distutils.extension import Extension from Cython.Build import cythonize ext_modules = [ Extension( r'num', [r'num.pyx'] ), ] setup( name="num", ext_modules=cythonize(ext_modules),

)

setup.py is normally used by Python to install the module it’s associated with, and can also be used to direct Python to compile C extensions for that module. Here we’re using setup.py to compile Cython code.

If you’re on Linux, and you have a C compiler installed (typically the case), you can compile the .pyx file to C by running the command: 

python setup.py build_ext --inplace

If you’re using Microsoft Windows and Microsoft Visual Studio 2017 or better, you’ll need to make sure you have the most recent version of setuptools installed in Python (version 46.1.3 as of this writing) before that command will work. This ensures that Python’s build tools will be able to auto-detect and use the version of Visual Studio you have installed.

If the compilation is successful, you should see new files appear in the directory: num.c (the C file generated by Cython) and a file with either a .o extension (on Linux) or a .pyd extension (on Windows). That’s the binary that the C file has been compiled into. You may also see a \build subdirectory, which contains the artifacts from the build process.

Run python main.py, and you should see something like the following returned as a response:

283.297530375

That’s the output from the compiled integral function, as invoked by our pure Python code. Try playing with the parameters passed to the function in main.py to see how the output changes.

Note that whenever you make changes to the .pyx file, you will need to recompile it. (Any changes you make to conventional Python code will take effect immediately.)

The resulting compiled file has no dependencies except the version of Python it was compiled for, and so can be bundled into a binary wheel. Note that if you refer to other libraries in your code, like NumPy (see below), you will need to provide those as part of the application’s requirements.

How to use Cython

Now that you know how to “Cythonize” a piece of code, the next step is to determine how your Python application can benefit from Cython. Where exactly should you apply it?

For best results, use Cython to optimize these kinds of Python functions:

  1. Functions that run in tight loops, or require long amounts of processing time in a single “hot spot” of code.
  2. Functions that perform numerical manipulations.
  3. Functions that work with objects that can be represented in pure C, such as basic numerical types, arrays, or structures, rather than Python object types like lists, dictionaries, or tuples.

Python has traditionally been less efficient at loops and numerical manipulations than other, non-interpreted languages. The more you decorate your code to indicate it should use base numerical types that can be turned into C, the faster it will do number-crunching.

Using Python object types in Cython isn’t itself a problem. Cython functions that use Python objects will still compile, and Python objects may be preferable when performance isn’t the top consideration. But any code that makes use of Python objects will be limited by the performance of the Python runtime, as Cython will generate code to directly address Python’s APIs and ABIs.

Another worthy target of Cython optimization is Python code that interacts directly with a C library. You can skip the Python “wrapper” code and interface with the libraries directly.

However, Cython does not automatically generate the proper call interfaces for those libraries. You will need to have Cython refer to the function signatures in the library’s header files, by way of a cdef extern from declaration. Note that if you don’t have the header files, Cython is forgiving enough to let you declare external function signatures that approximate the original headers. But use the originals whenever possible to be safe.

One external C library that Cython can use right out of the box is NumPy. To take advantage of Cython’s fast access to NumPy arrays, use cimport numpy (optionally with as np to keep its namespace distinct), and then use cdef statements to declare NumPy variables, such as cdef np.array or np.ndarray.

Cython profiling

The first step to improving an application’s performance is to profile it—to generate a detailed report of where the time is being spent during execution. Python provides built-in mechanisms for generating code profiles. Cython not only hooks into those mechanisms but has profiling tools of its own.

Python’s own profiler, cProfile, generates reports that show which functions take up the most amount of time in a given Python program. By default, Cython code doesn’t show up in those reports, but you can enable profiling on Cython code by inserting a compiler directive at the top of the .pyx file with functions you want to include in the profiling:

# cython: profile=True

You can also enable line-by-line tracing on the C code generated by Cython, but this imposes a lot of overhead, and so is turned off by default.

Note that profiling imposes a performance hit, so be sure to toggle profiling off for code that is being shipped into production.

Cython can also generate code reports that indicate how much of a given .pyx file is being converted to C, and how much of it remains Python code. To see this in action, edit the setup.py file in our example and add the following two lines at the top:

import Cython.Compiler.Options

Cython.Compiler.Options.annotate = True

(Alternatively, you can use a directive in setup.py to enable annotations, but the above method is often easier to work with.)

Ta bort .cfilerna som genereras i projektet och kör om setup.pyskriptet för att kompilera allt igen. När du är klar bör du se en HTML-fil i samma katalog som delar namnet på din .pyx-fil - i det här fallet  num.html. Öppna HTML-filen så ser du de delar av din kod som fortfarande är beroende av Python markerade med gult. Du kan klicka på de gula områdena för att se den underliggande C-koden som genereras av Cython.