当前位置:网站首页>Cython的使用

Cython的使用

2022-06-10 06:55:00 hxxjxw

cython的python的区别就在于,在cython里你也要对变量指定类型

我们知道python中是不需要对变量指定类型的,程序会自己判断,这也导致了python的运行慢

Python

x = 5

C/C++

int x = 5

Cython

cdef int x = 5
或
cpdef int x = 5

将python代码用cython编译

例如我们现在有python代码hxx_try.py

def hxx_test(x):
    y = 0
    for i in range(x):
        y += i
    return y

首先,将hxx_try.py修改后缀名为hxx_try.pyx, 然后新建setup.py 

setup.py

from setuptools import setup
from Cython.Build import cythonize

setup.py(
    name = 'hxx_learn_cython',
    ext_modules = cythonize("hxx_try.pyx"),
    zip_safe = False,
)

zip_safe=False要带着

 

 

然后

python setup.py build_ext --inplace

新生成.c文件,.so文件和build目录

 

 

目录结构是

 

 此时,新建一个python文件

from hxx_try import hxx_test
print(hxx_test(10))

就可以执行了

 

实际发挥作用的是hxx_try.cpython-38-x86_64-linux-gnu.so这个文件。将其他文件包括hxx_try.pyx删除,程序仍然可以执行

 

 

原网站

版权声明
本文为[hxxjxw]所创,转载请带上原文链接,感谢
https://blog.csdn.net/hxxjxw/article/details/125211698