gpt4 book ai didi

function - 我应该使用 def、cdef 或 cpdef 定义我的 Cython 函数以获得最佳性能吗?

转载 作者:行者123 更新时间:2023-12-04 16:42:11 26 4
gpt4 key购买 nike

假设我想要最佳性能,我如何知道在定义 Cython 函数时是使用 def、cdef 还是 cpdef?

最佳答案

如果您想要最佳性能,您应该知道如 this answer 中所述。一个相关的问题:

Once the function has been called there is no difference in the speed that the code inside a cdef and a def function runs at.



因此,为了获得最佳 Cython 性能,您应该 始终静态键入所有参数和变量 ,然后直觉上你会想使用 cdef ,但有一些注意事项我构建了下面的流程图(也基于前面提到的答案):

def, cdef, cpdef flowchart

此外,请注意:

cpdef functions cause Cython to generate a cdef function (that allows a quick function call from Cython) and a def function (which allows you to call it from Python). Interally the def function just calls the cdef function.



...以及来自 Cython 文档:

This exploits early binding so that cpdef functions may be as fast as possible when using C fundamental types (by using cdef). cpdef functions use dynamic binding when passed Python objects and this might much slower, perhaps as slow as def declared functions.



还有一个 case-specific benchmark in the Cython documentation (经常从 Python 调用该函数)产生以下结果:

enter image description here

关于function - 我应该使用 def、cdef 或 cpdef 定义我的 Cython 函数以获得最佳性能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49172528/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com