Cython(一)安装与使用

Cython

        Cython是让Python脚本支持C语言扩展的编译器,Cython能够将Python+C混合编码的.pyx脚本转换为C代码,主要用于优化Python脚本性能或Python调用C函数库。由于Python固有的性能差的问题,用C扩展Python成为提高Python性能常用方法,Cython算是较为常见的一种扩展方式。

在这里插入图片描述

Cython安装

       在Windows下Cython最便捷的安装方式是使用pip工具,安装命令如下所示

pip install cython

       成功安装后如下图所示

在这里插入图片描述
       当然,也可以从官网下载压缩包,解压后运行如下命令安装

python setup.py install

Cython文件编译

       Python是一门解释型语言,因此python不需要进行编译,但Cython的pyx必须要经过编译。编译步骤包括
       1、通过Cython将.pyx文件编译为.c文件
       2、通过C编译器将.c文件编译为pyd-windows(.so-linux),通过编译后的模块可以在python中通过import的形式进行调用,这一步通常是通过setuptools实现。
       下面通过经典的打印hello来说明cython文件编译过程
       1、新建hello.pyx文件,编写打印hello函数

def say_hello_to(name):
    print("Hello %s!" % name)

       2、编写setuptools setup.py如下,其中name表示模块名字,ext_modules表示编译包括的.pyx或者c文件,zip_safe置为False是为了防止使用python setup.py install编译时生成的 zipped egg文件无法在pxd文件中通过cimport方式运行的情况出现。

from setuptools import setup
from Cython.Build import cythonize

setup(
    name='Hello_world_app',
    ext_modules=cythonize("hello.pyx"),
    zip_safe=False,)

       3、在setup.py路径下打开cmd窗口,并运行如下命令

python setup.py build_ext --inplace

       编译成功后如下图所示

在这里插入图片描述
       4、在python中新建python_test.py脚本,调用打印hello模块

import hello

name = 'Li Ming'
hello.say_hello_to(name)

Cython代码运行

       1、Cython代码可以通过Jupyter notebook在Web界面中运行,Jupyter使用pip安装命令如下所示

pip install jupyter

       2、安装好后通过jupyter notebook命令调用

jupyter notebook

       3、将cython扩展加载到jupyter notebook中,然后运行cython代码
在这里插入图片描述
       4、若需要对cython代码进行详细分析,可使用命令%%cython --annotate
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/u010658002/article/details/107326665
今日推荐