詳解如何利用Cython為Python代碼加速,cythonpython

來源:互聯網
上載者:User

詳解如何利用Cython為Python代碼加速,cythonpython

引言

通常,在 Python 中寫迴圈(特別是多重迴圈)非常的慢,在文章 http://www.bkjia.com/article/133807.htm中,我們的元胞自動機的狀態更新函數 update_state 使用了兩重迴圈,所以我們嘗試用 Cython 重構該方法。

代碼

我們在同檔案夾下建立一個 update.pyx 檔案,寫入如下內容

import numpy as np cimport numpy as np cimport cythonDTYPE = np.floatctypedef np.float_t DTYPE_tdef update_state(np.ndarray[DTYPE_t, ndim=2] cells):  return update_state_c(cells)@cython.boundscheck(False)@cython.wraparound(False)cdef np.ndarray[DTYPE_t, ndim=2] update_state_c(np.ndarray[DTYPE_t, ndim=2] cells):  """更新一次狀態"""  cdef unsigned int i  cdef unsigned int j  cdef np.ndarray[DTYPE_t, ndim=2] buf = np.zeros((cells.shape[0], cells.shape[1]), dtype=DTYPE)  cdef DTYPE_t neighbor_num  for i in range(1, cells.shape[0] - 1):    for j in range(1, cells.shape[0] - 1):      # 計算該細胞周圍的存活細胞數            neighbor_num = cells[i, j-1] + cells[i, j+1] + cells[i+1, j] + cells[i-1, j] +\              cells[i-1, j-1] + cells[i-1, j+1] +\              cells[i+1, j-1] + cells[i+1, j+1]            if neighbor_num == 3:        buf[i, j] = 1      elif neighbor_num == 2:        buf[i, j] = cells[i, j]      else:        buf[i, j] = 0  return buf

update_state_c 函數上的兩個裝飾器是用來關閉 Cython 的邊界檢查的。

在同檔案下建立一個 setup.py 檔案

import numpy as npfrom distutils.core import setupfrom Cython.Build import cythonizesetup(  name="Cython Update State",  ext_modules=cythonize("update.pyx"),  include_dirs=[np.get_include()])

因為在 Cython 檔案中使用了 NumPy 的標頭檔,所以我們需要在 setup.py 將其包含進去。

執行 python setup.py build_ext --inplace 後,同檔案夾下會產生一個 update.cp36-win_amd64.pyd 的檔案,這就是編譯好的 C 擴充。

我們修改原始的代碼,首先在檔案頭部加入 import update as cupdate,然後修改更新方法如下

def update_state(self):  """更新一次狀態"""  self.cells = cupdate.update_state(self.cells)  self.timer += 1

將原方法名就改為 update_state_py 即可,運行指令碼,無異常。

測速

我們編寫一個方法來測試一下使用 Cython 可以帶來多少速度的提升

def test_time():  import time  game = GameOfLife(cells_shape=(60, 60))  t1 = time.time()  for _ in range(300):    game.update_state()  t2 = time.time()  print("Cython Use Time:", t2 - t1)  del game  game = GameOfLife(cells_shape=(60, 60))  t1 = time.time()  for _ in range(300):    game.update_state_py()  t2 = time.time()  print("Native Python Use Time:", t2 - t1)

運行該方法,在我的電腦上輸出如下

Cython Use Time: 0.007000446319580078
Native Python Use Time: 4.342248439788818

速度提升了 600 多倍。

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.