close

Python

關鍵字:python、 Cython、Model、C語言、加速、編譯、腳本、模組

Cython是將python轉換成C語言後執行,據說程式在C環境裡面執行速度高於python

以下就在Linux的作業系統下示範

先從下載安裝開始
使用pip3安裝Cython
pip3 install cython
創建資料夾
mkdir ABC
cd ABC
編寫文件hello.pyx當作程式腳本
vi hello.pyx
 
def print_hello(name):
    print "Hello %s!" % name
編寫文件setup.py,用來產生C語言腳本和model
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 pyx",
    cmdclass = {'build_ext': build_ext},
    ext_modules = ext_modules
)
執行編寫產出檔案hello.so和hello.c還有目錄build
hello.c是轉換成的C語言程式
hello.so是可被調用的model
python setup.py build_ext --inplace
最後再編寫一隻程式做測試,代入剛剛產生的腳本和model
匯入模組import hello
vi hello.py
 
#!/usr/bin/python
import hello
hello.print_hello("Saioyan")
執行指令
python3 hello.py
>> Hello Saioyan
 
本網站https://kk665403.pixnet.net/內之全部圖文,Saioyan梟夜所有,非經本人同意不得將全部或部分內容轉載於任何形式之媒體
Copyright © 2021 Saioyan. All rights reserved.
版權所有© 2021 Saioyan梟夜
arrow
arrow
    文章標籤
    python
    全站熱搜

    Saioyan梟夜 發表在 痞客邦 留言(0) 人氣()