Cython code differs from Python code __python

Source: Internet
Author: User

The code runs in Ipython-notebook and imports the Cython environment in Ipython-notebook.

1
%load_ext Cython

Cython can be doped with static types of C and C + + in Python, the Cython compiler can compile Cython source code into C or C + +, and the compiled code can be executed separately or used as a model in Python. The powerful thing about Cython is that Python and C can be combined to make the Cython code that looks like a Python language run at a similar speed to C.

We use a simple Fibonacci function to compare the difference between Python and Cython:

1
2
3
4
5
6
#python
def fib1 (n):
    a,b=0.0,1.0 for
    i in range (n):
        a,b=a+b,a return
    A

The following code uses the%%CYTHON flag to indicate that the following code uses Cython to compile

1
2
3
4
5
6 7
%%cython

def fib2 (int n):
    cdef double a=0.0, b=1.0 for
    i in range (n):
        a,b = a+b,a return
    A

By comparing the code above, in order to convert the dynamic type in Python to the static type in Cython, we use Cdef to define the variable i,a,b in the C language.
We use the C language to implement the Fibonacci function, and then through the Cython with Python encapsulation, which cfib.h for the Fibonacci function C language implementation, as follows:

1
2
3
4
5
6 7 8
Double Cfib (int n) {
  int i;
  Double a=0.0, b=1.0, tmp;
  For (i=0 i<n; ++i) {
    tmp = A; a = a + b; b = tmp;
  }
  return A;
}

1
2
3
4
5
6 7
%%cython

cdef extern from "/home/ldy/mega/python/cython/cfib.h":
    double cfib (int n)  
def fib3 (n):
    " "" "Returns the nth Fibonacci number.
    " " return CFIB (N)

To compare the elapsed time of different methods:

1
2
3
4
5
6
%timeit RESULT=FIB1 (1000)

%timeit result=fib2 (1000)%timeit result=fib3

(1000)
10000 loops, best 3:73.6µs per loop
1000000 loops, best 3:1.94µs per loop
1000000 loops, Best of 3:1. 92µs per loop
compilation of Cython code

The process of compiling Cython code into Python callable modules is mainly divided into two steps: The first step is to cython the compiler to optimize the Cython code into C or C + + code, and the second step is to use the C or C + + compiler to compile the generated C or C + + code to get the Python callable module.

We compile the Fib.pyxcython code written above with a setup.py script, as shown below, the key is in the third line, the function of cythonize is to convert Cython code into C code by Cython compiler, and the Setup function converts the resulting C code into Python adjustable with modules.

1
2
3
4
From Distutils.core Import Setup from
cython.build import cythonize
setup (ext_modules=cythonize (' Fib.pyx '))
#setup (ext_modules=cythonize (' *.pyx ', ' Fib1.pyx ') can also compile multiple Cython files at once

Once you have written the setup.py file, you can perform the compilation using the following command:

1
Python setup.py build_ext--inplace

After execution, FIB.C code and fib.so files are generated, and some intermediate results are saved in the build folder.

1
2
3
4
Import OS
os.chdir ('/home/ldy/mega/python/cython/test ')
os.getcwd ()
!ls
Build  fib.c  fib.pyx  fib.so  setup.py

Invoke the output fib.so module via python:

1
2
Import fib
fib.fib2 (90)
2.880067194370816e+18
definition of type in Cython

Why Cython and Python have a lot more performance, mainly for two points: first, Python is an interpreted language, and the Python interpreter interprets Python code as Python bytecode to run on Python virtual machines before running, The Python virtual machine translates the Python bytecode into a machine code that the CPU can execute, while the Cython code is directly compiled into a machine code that can be invoked by Python, and can be executed directly at runtime. The second major reason is that Python is a dynamic type, and the Python interpreter needs to judge the type when it interprets it, and then extract the data and operations it can run at the bottom. However, the C language and other relatively low-level language is static type, the compiler directly extracts the data for operation to generate machine code.

Use Cdef to define static types in Cython:

1
2
3
cdef int i
cdef int J
Cdef float F

You can also define more than one time:

1
2
3
4
CDEF:
    int i
    int J
    float F

Cython also allows simultaneous and reciprocal assignment of static and dynamic types:

1
2
3
4
5
6
%%cython
cdef int a=1,b=2,c=3
list_of_ints=[a,b,c]
list_of_ints.append (4)
a=list_of_ints[1]
Print A,list_of_ints
2 [1, 2, 3, 4]

Declaring Python types to be static types, Cython support to declare some python-built types such as list,tuple,dict as static types, so that they can be used like normal python types, but they need to be constrained to be the type they affirm. Can't change at will.

1 2 3 4 5 6 7 8 9 
%%cython cdef:list names dict name_num name_num={' Jerry ': 1, ' Tom ': 2, ' Bell ': 3} names=list (Name_num.keys ()) Print
The names other_names=names# dynamic type can initialize del other_names[0] #因为引用了同一个list from a static type of Python object, so the first element print is deleted names,other_names Other_names=tuple (other_names) #names和other_names的区别在于names只能是list类型, print other_names #other_names可以引用任何类型  
[' Bell ', ' Jerry ', ' Tom ']
[' Jerry ', ' Tom '] [' Jerry ', ' Tom ']
(' Jerry ', ' Tom ')
the use of numpy in Cython

We first construct a function to test the operation time using pure python to compare, the function of which is to gradient a pair of input images (do not have to pay too much attention to function, in this only use this function as a test). The input data for the function is indata a pixel-1400*1600 picture; output is outdata, for each pixel gradient value, the following is a pure Python implementation of this function:

1
2
3
4
5
6 7 8 9

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.