【发布时间】:2015-03-27 22:26:42
【问题描述】:
Cython 的新手(也许这是一个基本问题)。考虑两个都取自this blog here的例子:
# 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))
和
# 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 脚本编译第一个文件:
# 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 脚本:
# 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,而在第二种情况下,我使用cimport 导入numpy,使用cdef 声明变量但随后还在安装文件中包含numpy。
Cython 无论如何都会编译第一个代码(并且第一个代码似乎可以工作)。
在使用 Cython 编译(通过设置文件)之前使用 cimport 和 cdef 与在使用 Cython 编译之前(通过设置文件)不使用 cimport 和 cdef 有什么优势?
【问题讨论】:
标签: python-3.x cython