我应该使用def,cdef还是cpdef来定义我的Cython函数以获得最佳性能? [英] Should I define my Cython function using def, cdef, or cpdef for optimal performance?

查看:1380
本文介绍了我应该使用def,cdef还是cpdef来定义我的Cython函数以获得最佳性能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在定义Cython函数时,如何知道是否使用def,cdef或cpdef,假设我需要最佳性能? 如果你想获得最佳性能,你应该知道,如 此外,请注意:


cpdef 函数会导致Cython生成一个 cdef 函数(允许从Cython进行快速函数调用)和一个 def 函数(它允许您称之为来自Python)。整数 def 函数只是调用 cdef 函数。


...以及来自Cython文档:


这利用了早期绑定,因此<$ c $当使用C基本类型时(通过使用 cdef ),c> cpdef 函数可能会尽可能快。当传递Python对象时, cpdef 函数使用动态绑定,这可能会慢得多,可能低于 def 声明的函数。 / p>

还有一个


How can I know whether to use def, cdef or cpdef when defining a Cython function, assuming I want optimal performance?

解决方案

If you want optimal performance, you should know that as mentioned in this answer to a related question:

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.

So for optimal Cython performance you should always statically type all arguments and variables, and intuitively you would then be tempted to use cdef, but there are some caveats for which I constructed the flowchart below (also based on previously mentioned answer):

Furthermore, note that:

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.

... and from the Cython documentation:

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.

There exists also a case-specific benchmark in the Cython documentation (calling the function often and from Python) which yields the following result:

这篇关于我应该使用def,cdef还是cpdef来定义我的Cython函数以获得最佳性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆