This article is a memorandum that describes the minimum contents required to try out a Python library called Cython.
I hope it helps people who say, "Cython seems to be a way to speed up Python, but I'm not sure what it is!"
Don't be afraid to misunderstand
Cython = A new programming language insanely similar to Python ** for creating Python libraries **
is.
There are many other ways to use it, but I think this level of recognition is sufficient if you just try it first.
Let's try it right away.
The minimum required is two.
hoge.pyx
def tasu(a, b):
return a + b
It's very similar to Python, it's just like Python. In Cython, you can also define functions with cdef
and cpdef
, and you can specify the type of ʻaand
b`, but let's go without going deep because we are just trying.
setup.py
from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules=cythonize("hoge.pyx"))
There is a magical spell that ** does not ** the Cython code I wrote earlier.
When the above two are ready, transpile and build with the following command.
python3 setup.py build_ext -i
I think that some files have been generated, but the generated hoge.c
is a transpile of hoge.pyx
to C language. It is a library that is imported from Python and used by a person like hoge.cpython-36m-x86_64-linux-gnu.so
.
All you have to do now is import hoge.cpython-36m-x86_64-linux-gnu.so
and call the function you just created.
>>> import hoge
>>>
>>> print(hoge.tasu(1,2))
It seems that Cython does not receive much of the benefits of speeding up unless you know how to use it and where to use it, but it is surprisingly easy if you just try it.
Recommended Posts