python附加篇cpython用法
心得:剛換工作后,連續(xù)忙了2個(gè)多月,在這兩個(gè)多月里,學(xué)到的東西也是比較多的,不論從算法上,源碼調(diào)試上,還是代碼規(guī)范性上都有一定的提升,接下來(lái)會(huì)將這段時(shí)間接觸到內(nèi)容逐一記錄下來(lái)。先從cpython開始吧,cpython用作代碼保護(hù)或者能夠提升代碼運(yùn)行的效率。
Cpython官網(wǎng):https://cython.readthedocs.io/en/latest/index.html
中文版:https://cython.apachecn.org/#/docs/29?id=%e5%9f%ba%e6%9c%ac-setuppy
一、Cpython簡(jiǎn)介
CPython是特指C語(yǔ)言實(shí)現(xiàn)的Python,就是原汁原味的Python。主要目的做python的加速,當(dāng)然在編譯后,相應(yīng)的對(duì)代碼進(jìn)行了保護(hù)
二、快速開始,配置文件以及編譯
創(chuàng)建pyx文件:
hello.pyx
import timet0 = time.time() for i in range(100000):pass print("time is {}".format(time.time()-t0))setup.py
from setuptools import setup from Cython.Build import cythonizesetup(ext_modules=cythonize("hello.pyx") )命令行輸入python setup.py build_ext --inplace對(duì)hello.pyx文件進(jìn)行編譯
將會(huì)生成hello.的so動(dòng)態(tài)庫(kù),我們調(diào)用此so動(dòng)態(tài)庫(kù)即可。
test.py
cpython 輸出
time is 0.002833843231201172
我們用python同樣輸出
time is 0.005338907241821289
速度提高了一半左右,要是將大量的計(jì)算方入編譯,速度會(huì)有較高的提升
三、cpython中編碼注意事項(xiàng)
Python類型list,dict,tuple,等等可被用于靜態(tài)類型
變量類型定義,在pyx文件中定義好了才可以調(diào)用
cdef list foo = [] cdef dict fol = {} cdef (double, int) bar在函數(shù)中,如果未為參數(shù)或返回值指定類型,則假定該類型為Python對(duì)象。所以最好在入?yún)⒑头祷刂档臅r(shí)候定義變量類型
hello.py 如果變量輸出類型未定義則會(huì)輸出None
cdef list l=[1,2,3]def lis(int x,int y):cdef dict c ={}a = x + yl.append(a)c["lis"] = lreturn c輸出:
{'lis': [1, 2, 3, 3]}cpython中比如定義了列表,但經(jīng)過(guò)編譯后,沒(méi)辦法正常調(diào)用此列表,正確的方式是用函數(shù)去返回,用函數(shù)將列表包裝再返回。
也可以使用聲明類cdef,使它們成為Extension Types,它們的行為非常接近python類,但是速度更快,因?yàn)樗鼈兪褂胹truct 內(nèi)部存儲(chǔ)屬性。
from __future__ import print_functioncdef class Shrubbery:cdef list width, heightdef __init__(self, w, h):self.width = wself.height = hdef describe(self):print("This shrubbery is", self.width,"by", self.height, "cubits.")編譯后test.py
import newres = new.Shrubbery([1,2],[]) res.describe()##輸出 This shrubbery is [1, 2] by [] cubits.注意:將類編譯到cpython中后,從外面調(diào)用編譯過(guò)的類屬性是拿不到的,如果想拿對(duì)應(yīng)的類屬性,可以編寫對(duì)應(yīng)的方法來(lái)獲取屬性。
cdef class Shrubbery:cdef list width, heightdef __init__(self, w, h):self.width = wself.height = hprint(self.width,"width")print("my friends: ",my_friends())def describe(self):print("This shrubbery is", self.width,"by", self.height, "cubits.")def get_width(self):return self.width shr = hello.Shrubbery([1,2],[3,4]) shr.describe() print("width",shr.get_width())四、編譯
1. 基本的setup.py
如果只有一個(gè)Cython文件要轉(zhuǎn)換為已編譯的擴(kuò)展名,則使用filename example.pyx表示關(guān)聯(lián)setup.py 如下:
from setuptools import setup from Cython.Build import cythonizesetup(ext_modules = cythonize("example.pyx") )編譯:$ python setup.py build_ext --inplace
2. 包中的多個(gè)Cython文件
若要自動(dòng)編譯多個(gè)Cython文件而不顯式列出所有文件,可以使用全局模式:
setup(ext_modules = cythonize("package/*.pyx") )Extension如果通過(guò)它們,也可以在對(duì)象中使用全局模式cythonize():
extensions = [Extension("*", ["*.pyx"])]setup(ext_modules = cythonize(extensions) )3. 多個(gè)包時(shí),setup文件編寫
參考地址
from setuptools import Extension, setup from Cython.Build import cythonizesetup(ext_modules=cythonize("hello.pyx") )# include_dirs,libraries和library_dirs,它們指定鏈接到外部庫(kù)時(shí)在哪里可以找到.h和庫(kù)文件。 # module_list 可以是多個(gè)Extension也就是多個(gè)pyx文件 ext_modules = cythonize(module_list=[Extension(name="chello",sources=["test.pyx"],libraries=["hello"],include_dirs=['c2/include'],library_dirs=['c2/lib']), ])# ext_modules 要構(gòu)建的 Python 擴(kuò)展的列表 # packages distutils將操作的Python軟件包列表, 按包分發(fā),其他的還是元數(shù)據(jù),其中name最好是一定要到,如果安裝的話生成的文件會(huì)是指定name的名字 setup(name='chello',version="1.1.0",author="作者",ext_modules=ext_modules,description='Python Distribution Utilities',author_email='',url='',packages=['distutils', 'distutils.command'])總結(jié)
以上是生活随笔為你收集整理的python附加篇cpython用法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 【信号处理】基于小波变换的时间重分配多重
- 下一篇: nRF51822 入门必备教程(一篇搞定