|
|
话不多说,Hello World:
#hello.pyxdef say_hello_to(name): print("Hello %s!" % name)
#setup.pyfrom distutils.core import setupfrom distutils.extension import Extensionfrom Cython.Distutils import build_extext_modules = [Extension("hello", ["hello.pyx"])]setup( name = 'Hello world app', cmdclass = {'build_ext': build_ext}, ext_modules = ext_modules)
执行:
python setup.py build_ext --inplace
欧了~第一个cython算是完成,就是那个 hello.so的东东,如同普通的py文件一样使用即可。
可是,为毛要cython这么麻烦捏?速度啊速度!
def f(x): return x**2-xdef integrate_f(a, b, N): s = 0 dx = (b-a)/N for i in range(N): s += f(a+i*dx) return s * dx
cython一下,提高35%!还不满意?那么稍微再改改:
def f(double x): return x**2-xdef integrate_f(double a, double b, int N): cdef int i cdef double s, dx s = 0 dx = (b-a)/N for i in range(N): s += f(a+i*dx) return s * dx
4倍啊4倍!和原生的c一个级别了!!什么?还不满意?好吧,等我深入学习下先~ |
|