这里写自定义目录标题
Building a Cython module using setuptools
Imagine a simple “hello world” script in a file hello.pyx:
def say_hello_to(name):
print("Hello %s!" % name)
The following could be a corresponding setup.py script:
from setuptools import setup
from Cython.Build import cythonize
setup(
name='Hello world app',
ext_modules=cythonize("hello.pyx"),
zip_safe=False,
)
To build, run python setup.py build_ext --inplace. Then simply start a Python session and do from hello import say_hello_to and use the imported function as you see fit.
One caveat: the default action when running python setup.py install is to create a zipped egg file which will not work with cimport for pxd files when you try to use them from a dependent package. To prevent this, include zip_safe=False in the arguments to setup().
Faster code via static typing
1、纯python代码
def f(x):
return x ** 2 - x
def integrate_f(a, b, N):
s = 0
dx = (b - a) / N
for i in range(N):
s += f(a + i * dx)
return s * dx
for i in range(100):
integrate_f(0,100,100000)
运行时间:1.794s
2、纯python代码->cython
def f(x):
return x ** 2 - x
def integrate_f_cython_1(a, b, N):
s = 0
dx = (b - a) / N
for i in range(N):
s += f(a + i * dx)
return s * dx
for i in range(100):
integrate_f(0,100,100000)
运行时间:1.354s
3、增加变量类型声明
def f(double x):
return x ** 2 - x
def integrate_f_cython_2(double a, double b, int N):
cdef int i
cdef double s
cdef double dx
s = 0
dx = (b - a) / N
for i in range(N):
s += f(a + i * dx)
return s * dx
for i in range(100):
integrate_f(0,100,100000)
运行时间:0.336s
4、增加函数类型声明
3、增加变量类型声明
cdef double f(double x):
return x ** 2 - x
cdef double integrate_f_cython_4(double a, double b, int N):
cdef int i
cdef double s
cdef double dx
s = 0
dx = (b - a) / N
for i in range(N):
s += f(a + i * dx)
return s * dx
运行时间:0.161s
Determining where to add types
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 translate to pure C, while lines that require the Python C-API are yellow (darker as they translate to more C-API interaction). Lines that translate to C code have a plus (+) in front and can be clicked to show the generated code.
This report is invaluable when optimizing a function for speed, and for determining when to release the GIL: in general, a nogil block may contain only “white” code.