CPython
CPython安装
最近在弄模型加速,想着CPython
会不会比Python
要快,然后就试了下手。
安装一行命令的事情:
sudo pip install Cython --install-option="--no-cython-compile"
CPython安装验证
直接命令行输入cpython
就可以知道安装如何了
例子【例子源于参考Ref1,增加运行时间测试】
编写以 .pyx为扩展名的 cython程序,hello.pyx
def say_hello_to(name):
print("Hello %s!" % name)
编写python程序 setup.py
其目的是把 hello.pyx程序转化成hello.c ,并编译成so文件
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext_modules = [Extension("hello", ["hello.pyx"])]
setup(
name = 'Hello world app',
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules
)
执行python程序
python setup.py build_ext --inplace
执行的结果会生成两个文件:hello.c
和 hello.so
( 用PyObject* 封装好的文件)
用python
调用 hello.so
,调用文件为test.py
import hello
import time
start = time.time()
hello.say_hello_to("hi,cython!!")
print ("run time is {}".format(time.time() - start))