python - 如何在不使用 cythonizing 的情况下以纯 pythonic 方式优化 python 代码

标签 python optimization cython

编辑:

(与之前的版本相比,这篇文章已进行了大量编辑)。

为了测试目的,我有一个模块,比如 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.declarecython.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/

相关文章:

python - 艰难地学习 python 练习 35 帮助

performance - 为什么条件移动不易受到分支预测失败的影响?

java - 我应该复制实体模型吗?

python - cython.并行 : variable assignment without thread-locality

python - 为什么我的代码不能正确拆分扫描的 pdf 中的每一页?

python - self.finish() 将 Tornado Web 服务器置于什么状态?

python - 在没有输入的情况下将Python3输入设置为默认数字

algorithm - 有没有办法在比 O(n^3) 时间更好的时间内解决 4Sum 问题?

c++ - 使用 C 头文件错误编译 Cython

python - 在 Cython 代码中使用 float 文字而不是 double?