作者:李小文 算法工程師 Python愛好者社區專欄作者
知乎ID:https://www.zhihu.com/people/li_xiaowen/activities
作者其他好文傳送門:
協同過濾(ALS)的原理及Python實現
回歸樹的原理及Python實現
本文github:
https://github.com/tushushu/flying-python
1. Cython是什麼?Cython是一個程式語言,它通過類似Python的語法來編寫C擴展並可以被Python調用.既具備了Python快速開發的特點,又可以讓代碼運行起來像C一樣快,同時還可以方便地調用C library。
2. 如何安裝Cython?跟大多數的Python庫不同,Cython需要一個C編譯器,在不同的平臺上配置方法也不一樣。
2.1 配置gccwindows
安裝MingW-w64編譯器:
conda install libpython m2w64-toolchain -c msys2
在Python安裝路徑下找到\Lib\distutils文件夾,創建distutils.cfg寫入如下內容:
macOS
安裝XCode即可
linux: gcc一般都是配置好的,如果沒有就執行這條命令:
sudo apt-get install build-essential
%load_ext Cython
%%cython
cdef int a = 0
for i in range(10):
a += i
print(a)
常規Python函數,運行時間559 ns
Cython def函數,聲明一個Python函數,既可以在模塊內調用,也可以在模塊外調用。模塊內運行時間524.2 ns,模塊外運行時間512 ns
Cython cpdef函數,聲明一個C函數和一個Python wrapper,在模塊內被當做C函數調用,在模塊外被.py文件當做Python函數調用。模塊內運行時間43.7 ns,模塊外運行時間81.7 ns
Cython cdef函數,聲明一個C函數,不可以在模塊外被Python調用。模塊內運行時間34.8 ns
4.1 常規Python函數def f(x):
return x ** 2 - x
%timeit f(100)
%%cython
from time import time
def f1(x):
return x ** 2 - x
n = 10000000
start = time()
for _ in range(n):
f1(100)
end = time()
run_time = (end - start) / n * 1000 * 1000 * 1000
print("%.1f ns" % run_time)
%timeit f1(100)
%%cython
from time import time
cpdef long f2(long x):
return x ** 2 - x
n = 10000000
start = time()
for _ in range(n):
f2(100)
end = time()
run_time = (end - start) / n * 1000 * 1000 * 1000
print("%.1f ns" % run_time)
%timeit f2(100)
%%cython
from time import time
cdef long f3(long x):
return x ** 2 - x
n = 10000000
start = time()
for _ in range(n):
f3(100)
end = time()
run_time = (end - start) / n * 1000 * 1000 * 1000
print("%.1f ns" % run_time)
常規Python函數,運行時間549微秒
Python內置函數,運行時間104微秒
Cython函數,運行時間51.6微秒
5.1 常規Python函數def sum_list(A):
ret = 0
for x in A:
ret += x
return ret
%timeit sum_list(A)
%%cython
cpdef int sum_list_cython(A):
cdef int ret, x
for x in A:
ret += x
return ret
%timeit sum_list_cython(A)
from time import time
cdef long f4(long x):
return x ** 2 - x
if __name__ == "__main__":
cdef int x = 3
print(f4(x))
部分內容引用自 - Cython官方文檔
http://link.zhihu.com/?target=http%3A//docs.cython.org/en/latest/index.html
作者其他好文傳送門:
協同過濾(ALS)的原理及Python實現
回歸樹的原理及Python實現
Python的愛好者社區歷史文章大合集:
Python的愛好者社區歷史文章列表
福利:文末掃碼關注公眾號,「Python愛好者社區」,開始學習Python課程:
關注後在公眾號內回復「 課程 」即可獲取:
小編的轉行入職數據科學(數據分析挖掘/機器學習方向)【最新免費】
小編的Python的入門免費視頻課程!
小編的Python的快速上手matplotlib可視化庫!
崔老師爬蟲實戰案例免費學習視頻。
陳老師數據分析報告擴展製作免費學習視頻。
玩轉大數據分析!Spark2.X + Python精華實戰課程免費學習視頻。