Cython 新手(也许这是一个基本问题)。考虑两个例子,两者都取自这个博客在这里 http://technicaldiscovery.blogspot.com/2011/06/speeding-up-python-numpy-cython-and.html:
# code 1
import numpy as np
def num_update(u):
u[1:-1,1:-1] = ((u[2:,1:-1]+u[:-2,1:-1])*dy2 +
(u[1:-1,2:] + u[1:-1,:-2])*dx2) / (2*(dx2+dy2))
and
# code 2
cimport numpy as np
def cy_update(np.ndarray[double, ndim=2] u, double dx2, double dy2):
cdef unsigned int i, j
for i in xrange(1,u.shape[0]-1):
for j in xrange(1, u.shape[1]-1):
u[i,j] = ((u[i+1, j] + u[i-1, j]) * dy2 +
(u[i, j+1] + u[i, j-1]) * dx2) / (2*(dx2+dy2))
假设我使用以下内容编译第一个文件setup.py
script:
# setup file for code 1
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext = Extension("laplace", ["laplace.pyx"],)
setup(ext_modules=[ext], cmdclass = {'build_ext': build_ext})
第二个文件包含以下内容setup.py
script:
# setup file for code 2
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy
ext = Extension("laplace", ["laplace.pyx"],
include_dirs = [numpy.get_include()])
setup(ext_modules=[ext], cmdclass = {'build_ext': build_ext})
在第一种情况下,我使用常规numpy
并且没有导入numpy
在设置文件中,而在第二种情况下我导入了numpy
using cimport
,使用声明变量cdef
但随后也包括在内numpy
在安装文件中。
Cython
无论如何都会编译第一个代码(并且第一个代码似乎可以工作)。
使用有什么好处cimport
and cdef
在使用 Cython 编译之前(通过安装文件)与不使用cimport
and cdef
在使用 Cython 编译之前(通过安装文件)?