python - 为 python 模块创建 .pxd 文件

标签 python cython

一种使用 cython 的方法,cython 是 Python 到 C 的编译器, 不是在 Cython 中重写 Python 代码,而是编写一个与您声明变量类型的模块同名的 .pxd 文件,如 here 中所述。

有谁知道自动化或半自动化此过程的方法吗?

最佳答案

您具体要自动化什么? Cython 可以采用 python 模块并将其编译成 C,但这只能实现适度的速度提升。大部分速度提升来自于提供类型声明。这真的不是你可以自动化的事情。您必须为他们提供一种或另一种方式以获得最佳速度提升。

您可以将类型声明放在 .py 文件本身中。在 Python 解释器中运行时,类型声明无效。但是在编译时,cython 可以使用它们进行某些优化。例如。

some_module.py

def myfunction(x, y=2):
    a = x-y
return a + x * y

some_module.pxd

cpdef int myfunction(int x, int y=*)

可以改写为:

(a) 使用装饰器

@cython.locals(x=cython.int, y=cython.int, a=cython.int)
@cython.returns(cython.int)
def myfunction(x, y=2):
    a = x-y
    return a + x * y

或者,(b) 使用注解

# cython: annotation_typing=True

def myfunction(x: {'ctype': 'int'}, y: {'ctype': 'int'}=2) -> {'ctype': 'int'}:
    a = x-y
    return a + x * y

关于python - 为 python 模块创建 .pxd 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37503462/

相关文章:

python - Cython 中的这个 malloc'ed 数组发生了什么?

python - 如何检查元素是否在屏幕上完全可见?

当从未调用 issubclass() 时,Python 在 issubclass() 上抛出 TypeError

Python 等效于 R c() 函数,用于数据框列索引?

python - 包装一个函数,该函数返回一个指向带有 ctypes 的 python 对象的指针

python - 将 Clang 设置为 Windows 上 pip install 中使用的默认编译器

python - 更改数据框的数据类型以使用该数据进行数据可视化的明确目的

c++ - python中的对象与实例

python - 使用 cython 从 c 调用 python 代码

python - 如何用Cython包装Tensorflow并让C++调用它?