使用 cython(Python 到 C 编译器)的一种方法是,不用在 Cython 中重写 Python 代码,而只需编写一个与声明变量类型的模块同名的 .pxd 文件,如此处所述
有谁知道如何自动化或半自动化此过程?
您具体想实现什么自动化?Cython 可以采用 python 模块并将其编译为 C,但这只能实现适度的速度提升。大部分速度的提高来自于提供类型声明。这确实不是你可以自动化的事情。您必须以一种或另一种方式提供它们以获得最佳的速度提升。
您可以将类型声明放在.py文件本身中。当在 Python 解释器中运行时,类型声明不起作用。但编译后,cython 可以使用它们进行某些优化。例如。
一些_模块.py
def myfunction(x, y=2):
a = x-y
return a + x * y
Run Code Online (Sandbox Code Playgroud)
一些_模块.pxd
cpdef int myfunction(int x, int y=*)
Run Code Online (Sandbox Code Playgroud)
可以写成:
(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
Run Code Online (Sandbox Code Playgroud)
或者,(b) 使用注释
# cython: annotation_typing=True
def myfunction(x: {'ctype': 'int'}, y: {'ctype': 'int'}=2) -> {'ctype': 'int'}:
a = x-y
return a + x * y
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2017 次 |
| 最近记录: |