ctypes vs C extension

谁说胖子不能爱 提交于 2019-11-30 17:27:51

I've compared the performance of a C extension vs. a ctypes wrapper. In my particular test, the difference was about 250x. There were multiple calls into the C library so the ctypes wrapper was also executing Python code. The running time for the C library was very short which made the extra overhead for Python code even more significant. So the ratio will likely be different for you but was significant in my case.

The directly C coded interface has the potential to be much much faster. The bottleneck is the interface from Python to C and marshalling arguments and results may for example involve copying strings or converting Python lists to/from C arrays. If you have a loop that makes several hundred of these calls and some of the data doesn't have to be marshalled separately for each call then all you have to do is recode the loop in C and you may be able to massively reduce the bottleneck. ctypes doesn't give you that option: all you can do is call the existing functions directly.

Of course that all depends on exactly what sort of functions you are calling and what sort of data you are passing around. It may be that you can't reduce the overheads in which case I would still expect ctypes to be slower but perhaps not significantly.

Your best best would be to put together some sample of your code written each way and benchmark it. Otherwise there are just too many variables for a definitive answer.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!