What is Cython?
Xiaobian to share with you what Cython is, I believe most people do not know how, so share this article for everyone's reference, I hope you have a lot of harvest after reading this article, let's go to understand it together!
1. What is Cython?
Cython is a programming language that uses Python like syntax to write C extensions and can be called by Python. It combines Python's fast development features with the ability to make code run as fast as C, and it's easy to call C libraries.
2. How to install Cython?
Unlike most Python libraries, Cython requires a C compiler and is configured differently on different platforms.
2.1 Configure gcc
windows
Install MingW-w64 compiler: conda install libpython m2w64-toolchain -c msys2
Find the\Lib\distutils folder in the Python installation path and create distutils.cfg Write the following:
[build] compiler=mingw32
macOS
Install XCode
linux:
gcc is generally configured, if not, execute this command: sudo apt-get install build-essential
2.2 Install cython library
If Anaconda is not installed: pip install cython
If Anaconda is installed: conda install cython
3. Cython on Jupyter Notebook
First load the Cython extension, using the magic command %load_ext Cython
Next run Cython code using magic command %%cython
%load_ext Cython
%%cython
#Sum natural numbers from 1 to-100
total = 0
for i in range(1, 101):
total += i
print(total)
5050
4. How fast is Cython?
Python function, runtime 261 ns
Cython function, runtime 44.1 ns
Running time is only about one-fifth of the original, the secret is that the parameter x uses a static type int, avoiding the time-consuming type checking.
4.1 Python function
def f(x):
return x ** 2 - x
%timeit f(100)
261 ns ± 8.78 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
4.2 Cython functions
%%cython
def g(int x):
return x ** 2 - x
%timeit g(100)
44.1 ns ± 1.09 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
The above is all the content of "Cython is what" this article, thank you for reading! I believe that everyone has a certain understanding, hope to share the content to help everyone, if you still want to learn more knowledge, welcome to pay attention to the industry information channel!