Python性能提升系列之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.chello.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))

Ref:
1、https://m.pythontab.com/article/1110

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值