Samouczek Cythona: Jak przyspieszyć Pythona

Python to potężny język programowania, który jest łatwy do nauczenia i łatwy w obsłudze, ale nie zawsze jest najszybszy do uruchomienia - zwłaszcza gdy masz do czynienia z matematyką lub statystyką. Biblioteki innych firm, takie jak NumPy, które zawijają biblioteki C, mogą znacznie poprawić wydajność niektórych operacji, ale czasami potrzebujesz tylko surowej szybkości i mocy języka C bezpośrednio w Pythonie.

Cython został opracowany, aby ułatwić pisanie rozszerzeń C dla Pythona i umożliwić przekształcenie istniejącego kodu Pythona w C. Co więcej, Cython pozwala na dostarczanie zoptymalizowanego kodu z aplikacją Python bez zewnętrznych zależności.

W tym samouczku omówimy kroki potrzebne do przekształcenia istniejącego kodu Pythona w Cython i wykorzystania go w aplikacji produkcyjnej.

Powiązane wideo: Używanie Cythona do przyspieszenia Pythona

Przykład Cythona

Zacznijmy od prostego przykładu zaczerpniętego z dokumentacji Cythona, niezbyt wydajnej implementacji funkcji całkowej:

def f (x):

    powrót x ** 2-x

def integrate_f (a, b, N):

    s = 0

    dx = (ba) / N

    dla i w zakresie (N):

        s + = f (a + i * dx)

    powrót s * dx

Kod jest łatwy do odczytania i zrozumienia, ale działa wolno. Dzieje się tak, ponieważ Python musi nieustannie konwertować między swoimi własnymi typami obiektów a surowymi typami liczbowymi maszyny.

Teraz rozważ wersję Cython tego samego kodu, z podkreślonymi dodatkami Cythona:

 cdef f (podwójne x):

    powrót x ** 2-x

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

    cdef int i

    cdef double s, x, dx

    s = 0

    dx = (ba) / N

    dla i w zakresie (N):

        s + = f (a + i * dx)

    powrót s * dx

Te dodatki pozwalają nam jawnie deklarować typy zmiennych w całym kodzie, dzięki czemu kompilator Cython może przetłumaczyć te „ozdobione” dodatki na język C. 

Powiązany film: Jak Python ułatwia programowanie

Idealny dla IT, Python upraszcza wiele rodzajów pracy, od automatyzacji systemu po pracę w najnowocześniejszych dziedzinach, takich jak uczenie maszynowe.

Składnia Cythona

Słowa kluczowe używane do ozdabiania kodu Cythona nie występują w konwencjonalnej składni Pythona. Zostały opracowane specjalnie dla Cythona, więc każdy ozdobiony nimi kod nie będzie działał jako konwencjonalny program w Pythonie.

Oto najczęstsze elementy składni Cythona:

Typy zmienne

Niektóre z typów zmiennych wykorzystywanych w Cython są echa własnych typów Pythona, takie jak  int, floati long. Inne typy zmiennych Cython można również znaleźć w C, takie jak charlub struct, podobnie jak deklaracje, takie jak unsigned long. Inne są unikalne dla Cythona, na przykład bintreprezentacja True/Falsewartości Pythona na poziomie C.

cdefI cpdeftypy funkcyjne

cdefKluczowe wskazuje na wykorzystanie typu Cython lub C. Jest również używany do definiowania funkcji, tak jak w Pythonie.

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.)

Usuń .cpliki wygenerowane w projekcie i ponownie uruchom setup.pyskrypt, aby ponownie skompilować wszystko. Kiedy skończysz, powinieneś zobaczyć plik HTML w tym samym katalogu, który ma taką samą nazwę jak Twój plik .pyx - w tym przypadku  num.html. Otwórz plik HTML, a zobaczysz części kodu, które nadal są zależne od Pythona, podświetlone na żółto. Możesz kliknąć żółte obszary, aby zobaczyć podstawowy kod C wygenerowany przez Cython.