编辑:
(与之前的版本相比,这篇文章已进行了大量编辑)。
为了测试目的,我有一个模块,比如 ptest.py
:
# ptest.py
def testfunc(*args) :
# Some process that can take significant time. There may be some integers larger than 2^64.
将其 cythonizing 后,比如说,ctest.pyx
我通过一些进一步的测试(如预期的那样)提高了性能。
现在对于一些足够大的整数值,程序可能会抛出 OverflowError
而在纯 python 中这可能不会发生。在这种情况下,我可以像在 python 中那样在 cython 中使用信息(例如,ValueError('The number should not be greater than some value')
)引发 SomeError
吗?
我也是这样
if n > 2**64:
raise ValueError("Number should be a non negative integer less than 2^64.")
它一直显示:OverflowError: Python int too large to convert to C unsigned long
。似乎完全忽略了条件。
那么,我该如何通知用户呢?最后,我可以在纯 python 中使用 cython 而不对整个程序进行 cython 化(即没有设置、构建等),因为我不想失去 python 的那些功能(在这种情况下引发异常、处理足够大的整数等。 )?
我尝试了 cython
模块中的其他方法(遵循 Cython
文档),例如 cython.declare
、cython.exceptval
等在 .py
文件中,但它们似乎都未能提高性能。我还没有接触过 ctypes
,因为我想事先了解适当的技术。
最佳答案
我对值为 n==1_000 的 OP 代码计时并运行了 10_000 次。持续时间约为 0.77 秒
更改代码以使用列表理解如下:
def testfunc(n: int) -> list :
return [n_ for n_ in range(n, 0, -1)]
...将持续时间减少到 ~0.26 秒
关于python - 如何在不使用 cythonizing 的情况下以纯 pythonic 方式优化 python 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70576193/