【问题标题】:cython compilation - import vs cimportcython 编译 - 导入与 cimport
【发布时间】: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 编译(通过设置文件)之前使用 cimportcdef 与在使用 Cython 编译之前(通过设置文件)不使用 cimportcdef 有什么优势?

【问题讨论】:

    标签: python-3.x cython


    【解决方案1】:

    Cython 中的import numpy 与 Python 相同,但 cimport numpy 告诉 Cython 加载声明文件:

    https://github.com/cython/cython/blob/master/Cython/Includes/numpy/init.pxd

    where 声明了所有 C-API 函数、常量和类型,还包括头文件,例如 numpy/arrayobject.h

    如果您使用 np.ndarray[...] 声明变量,Cython 将知道如何将数组元素访问转换为 c 代码,这比 Python 的 [] 运算符快得多。

    你需要告诉c编译器setup.py中的numpy头文件在哪里,所以你调用numpy.get_include()来获取路径。

    【讨论】:

      【解决方案2】:

      Cython 可以编译普通的 python 代码,所以你的第一个可以编译。

      一般来说,你为 cython 标记的类型越多,你获得更好性能的机会就越大。因此,如果您想以灵活性换取速度,那是您的决定。

      运行 cython -a your_test.pyx 以查看 cython 如何编译您的代码的注释版本。黄色表示您的代码转换为大量 C 代码(这大致意味着性能损失),而白色表示它仅转换为几行 C。

      如果你没有花时间在这里问,而是在官网上阅读guide,你可能已经有更好的了解了。

      【讨论】:

      • 我试过了,但什么也没发生(不知道在哪里可以看到黄白注释版本)。我正在使用 Pycharm 和带有 IDE 的终端窗口
      • 它将在存储源文件的同一位置生成一个 html 文件 - 看看那里。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-05
      • 2017-11-24
      • 2014-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多