Cython叫做C-Extensions for Python
Cython is a programming language that makes writing C extensions for the Python language as easy as Python itself. It aims to become a superset of the [Python] language which gives it high-level, object-oriented, functional, and dynamic programming. Its main feature on top of these is support for optional static type declarations as part of the language. The source code gets translated into optimized C/C++ code and compiled as Python extension modules. This allows for both very fast program execution and tight integration with external C libraries, while keeping up the high programmer productivity for which the Python language is well known.
Cython也是一门语言
安装只需要
pip install cython
Cython的好处在于,让对C/C++不太了解的人也能编写程序,它能够为你生成C code,然后你调用就行了
我们可能经常会被问一个问题,在AI领域为什么大家都用Python编程,为什么不用C/C++,那样会快很多
If you've done much Python programming and shared it with your non-Python programmer friends and colleagues , chances are, you've been inquired about why you're using Python, since, of course, it's such a "slow" language!
Isn't Python slow? What about the GIL? That dynamic typing though?
I find myself frequently defending Python by explaining that, while pure Python is indeed quite slow, Python in practice is not. Libraries like Numpy, Pandas, and Scikit-learn all are C Optimized. When you use them, you're actually making use of C/C++ power, you're just able to use Python syntax. In fact, Numpy, Pandas, and Scikit-learn all make use of Cython! Chances are, the Python+C-optimized code in these popular libraries and/or using Cython is going to be far faster than the C code you might write yourself, and that's if you manage to write it without any bugs.
这是因为我们实际上并不是只是在用Python,我们用的是Python语言包裹的C/C++。很多库都是C optimized library(像numpy, pandas), 然后提供了一个Python API for you
当你想实现某些事情的时候,在常规的情况下,你会发现已经有实现好的C optimized library供你使用了。但是也有一些unique的情况,这个时候,你就可以通过自己写cython来实现C加速的python程序
众所周知,Python是一种非常简单易上手的胶水语言(胶水语言的意思就是用来连接软件组件的程序设计语言,通常是脚本语言)。尽管近年来Python越来越火,也被各种吹捧,但它的执行速度始终逃不出被人所诟病的窘境。不过好在目前已经有不少较为成熟的解决方案来为Python提速,Cython就是一种非常不错的解决方案
Cython也是一种编程语言,按照官方文档里的说法,它可以通过类似Python的语法来编写可以被Python调用的C扩展。从而,在保留Python快速开发的优点的同时,可以提升Python速度并方便地调用外部C库。
总结一下,利用Cython,我们可以:
- 利用Python的语法实现Python和C/C++的混合编程,从而可以提升Python的执行效率;
- 调用C/C++代码。
最后,扫个盲,请注意Cython≠CPython。CPython的意思是,用C语言开发的Python解释器。换句话说,就是Python只是一种编程语言,具体实现的时候,如果用C来实现,那就叫CPython,如果用Java来实现,那就叫Jython,如果用C#来实现,那就叫IronPython,如果用Python自己来实现,那就叫PyPy。
cpython文件后缀名是.pyx
Cython (pyx)
于 2021-04-30 09:41:49 首次发布