apple_cy.pyx
cpdef int def test(int x):
cdef int y = 0
cdef int i
for i in range(x):
y += i
return y
from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules = cythonize('apple_cy.pyx'))
python setup.py build_ext --inplace
生成了如下文件
使用生成的pyd文件
testing.py
import apple_cy
sum = apple_cy.test(10)
print(sum)
可以使用如下代码来计算apple_cy.*.pyd的耗时
import timeit
cost = timeit.timeit('apple_cy.test(10)', setup='import apple_cy', number=100)
print(cost)
cdef,cpdef和def的区别:cdef定义的函数其实是C语言函数的原型,其只能被Python的函数进行调用,而不能被Python直接调用;cpdef除了能实现cdef的功能,其也能被python直接调用,但是变量的类型必须在C语言和Python中都存在才可以(尽量避免使用cpdef);def定义的函数可以直接被Python可调用,def定义的函数内也可调用cdef定义的函数。