`
iyuan
  • 浏览: 463360 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

cython初涉

阅读更多
话不多说,Hello World:
#hello.pyx
def say_hello_to(name):
    print("Hello %s!" % name)

#setup.py
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext

ext_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-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

cython一下,提高35%!还不满意?那么稍微再改改:
def f(double x):
    return x**2-x

def 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一个级别了!!什么?还不满意?好吧,等我深入学习下先~
0
3
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics