Vodič za Cython: Kako ubrzati Python

Python je moćan programski jezik koji je jednostavan za naučiti i s kojim je lako raditi, ali nije uvijek najbrži za pokretanje - pogotovo kada se bavite matematikom ili statistikom. Neovisne knjižnice poput NumPy, koje omotavaju C knjižnice, mogu značajno poboljšati izvedbu nekih operacija, ali ponekad vam samo trebaju sirova brzina i snaga C izravno u Pythonu.

Cython je razvijen kako bi se olakšalo pisanje C proširenja za Python i kako bi se omogućio transformiranje postojećeg Python koda u C. Štoviše, Cython omogućuje isporuku optimiziranog koda s Python aplikacijom bez vanjskih ovisnosti.

U ovom uputstvu proći ćemo kroz korake potrebne za transformiranje postojećeg Python koda u Cython i njegovu upotrebu u proizvodnoj aplikaciji.

Povezani video: Korištenje Cythona za ubrzavanje Pythona

Primjer Cythona

Počnimo s jednostavnim primjerom preuzetim iz Cythonove dokumentacije, ne baš učinkovitom implementacijom integralne funkcije:

def f (x):

    povrat x ** 2-x

def integrate_f (a, b, N):

    s = 0

    dx = (ba) / N

    za i u opsegu (N):

        s + = f (a + i * dx)

    povratak s * dx

Kôd je lako pročitati i razumjeti, ali radi sporo. To je zato što Python mora neprestano pretvarati naprijed-natrag između vlastitih vrsta objekata i sirovih numeričkih vrsta stroja.

Sada razmotrite Cython verziju istog koda, s podcrtanim Cythonovim dodacima:

 cdef f (dvostruki x):

    povrat x ** 2-x

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

    cdef int i

    cdef dvostruki s, x, dx

    s = 0

    dx = (ba) / N

    za i u opsegu (N):

        s + = f (a + i * dx)

    povratak s * dx

Ovi dodaci omogućuju nam izričito deklariranje vrsta varijabli u cijelom kodu, tako da kompajler Cython može prevesti te "ukrašene" dodatke u C. 

Povezani video: Kako Python olakšava programiranje

Savršen za IT, Python pojednostavljuje mnoge vrste poslova, od automatizacije sustava do rada u najmodernijim poljima poput strojnog učenja.

Cython sintaksa

Ključne riječi korištene za ukrašavanje Cython koda nisu pronađene u uobičajenoj Python sintaksi. Razvijeni su posebno za Cython, tako da bilo koji kod ukrašen njima neće raditi kao uobičajeni Python program.

Ovo su najčešći elementi Cythonove sintakse:

Vrste varijabli

Neki od tipova varijabla koja se koristi u Cython su odjeci Python vlastite vrste, kao što su  int, floati long. Ostale vrste Cython varijabli također se nalaze u C, poput charili struct, kao i deklaracije like unsigned long. A drugi su jedinstveni za Cython, poput bintpredstavljanja Python True/Falsevrijednosti na razini C.

cdefI cpdefvrste funkcija

cdefKljučna riječ označava korištenje Cython ili C tipa. Također se koristi za definiranje funkcija kao što biste to učinili u Pythonu.

Funkcije napisane u Cythonu pomoću defključne riječi Python vidljive su drugim Python kodima , ali imaju kažnjavanje za izvedbu. Funkcije koje koriste cdefključnu riječ vidljive su samo drugim Cython ili C kodima, ali se izvršavaju mnogo brže. Ako imate funkcije koje se interno pozivaju unutar modula Cython, koristite cdef.

Treća ključna riječ, cpdefpruža kompatibilnost s Python kodom i C kodom, na takav način da C kôd može pristupiti deklariranoj funkciji punom brzinom. Ova pogodnost ipak košta, ali  cpdeffunkcije generiraju više koda i imaju malo više troškova od poziva cdef.

Ostale ključne riječi Cython

Ostale ključne riječi u Cythonu pružaju kontrolu nad aspektima tijeka programa i ponašanja koji nisu dostupni u Pythonu:

  • gili nogil. To su upravitelji konteksta koji se koriste za razgraničenje odjeljaka koda koji zahtijevaju ( with gil:) ili ne zahtijevaju ( with nogil:) Pythonovo globalno zaključavanje tumača ili GIL. C kôd koji ne upućuje pozive Python API-ju može se brže izvoditi u nogilbloku, posebno ako izvodi dugotrajnu operaciju kao što je čitanje s mrežne veze.
  • cimportTo usmjerava Cython na uvoz C vrsta podataka, funkcija, varijabli i tipova proširenja. Cython aplikacije koje koriste NumPyjeve matične C module, na primjer, koriste se cimportza pristup tim funkcijama.
  • include. Ovo smješta izvorni kod jedne Cython datoteke u drugu, na približno isti način kao u C. Imajte na umu da Cython ima sofisticiraniji način dijeljenja deklaracija između Cython datoteka koje nisu samo includes.
  • ctypedef. Upotrebljava se za upućivanje na definicije tipova u vanjskim C datotekama zaglavlja.
  • extern. Koristi se cdefza označavanje C funkcija ili varijabli koje se nalaze u drugim modulima.
  • public/api. Koristi se za izradu deklaracija u modulima Cython koje će biti vidljive ostalim C kodovima.
  • inline. Upotrebljava se za označavanje da zadana funkcija treba biti ugrađena ili njezin kôd smjestiti u tijelo pozivne funkcije kad god se koristi, radi brzine. Na primjer, ffunkcija u gornjem primjeru koda može biti ukrašena inlinekako bi smanjila opće troškove poziva funkcije jer se koristi samo na jednom mjestu. (Imajte na umu da bi prevodilac C mogao automatski izvršiti vlastitu ugradnju, ali inlinevam omogućuje izričito određivanje treba li nešto ugraditi.)

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

Izbrišite .cdatoteke generirane u projektu i ponovo pokrenite setup.pyskriptu da biste sve prekompajlirali. Kada završite, trebali biste vidjeti HTML datoteku u istom direktoriju koji dijeli ime vašeg .pyx datoteke u ovom slučaju,  num.html. Otvorite HTML datoteku i vidjet ćete dijelove koda koji još uvijek ovise o Pythonu označeni žutom bojom. Možete kliknuti na žuta područja da biste vidjeli temeljni C kod koji je generirao Cython.