利用ctypes提高Python的執行速度,ctypespython

來源:互聯網
上載者:User

利用ctypes提高Python的執行速度,ctypespython

前言

ctypes是Python的外部函數庫。它提供了C相容的資料類型,並且允許調用動態連結程式庫/共用庫中的函數。它可以將這些庫封裝起來給Python使用。這個引入C語言的介面可以協助我們做很多事情,比如需要調用C代碼的來提高效能的一些小型問題。通過它你可以接入Windows系統上的 kernel32.dll 和 msvcrt.dll 動態連結程式庫,以及Linux系統上的 libc.so.6 庫。當然你也可以使用自己的編譯好的共用庫

我們先來看一個簡單的例子 我們使用 Python 求 1000000 以內素數,重複這個過程10次,並計算已耗用時間。

import mathfrom timeit import timeitdef check_prime(x):  values = xrange(2, int(math.sqrt(x)) + 1)  for i in values:    if x % i == 0:      return False  return Truedef get_prime(n):  return [x for x in xrange(2, n) if check_prime(x)]print timeit(stmt='get_prime(1000000)', setup='from __main__ import get_prime',       number=10)

輸出

42.8259568214

下面用C語言寫一個的 check_prime 函數,然後把它當作共用庫(動態連結程式庫)匯入

#include <stdio.h>#include <math.h>int check_prime(int a){  int c;  for ( c = 2 ; c <= sqrt(a) ; c++ ) {    if ( a%c == 0 )      return 0;  }  return 1;}

使用以下命令產生 .so (shared object)檔案

gcc -shared -o prime.so -fPIC prime.c
import ctypesimport mathfrom timeit import timeitcheck_prime_in_c = ctypes.CDLL('./prime.so').check_primedef check_prime_in_py(x):  values = xrange(2, int(math.sqrt(x)) + 1)  for i in values:    if x % i == 0:      return False  return Truedef get_prime_in_c(n):  return [x for x in xrange(2, n) if check_prime_in_c(x)]def get_prime_in_py(n):  return [x for x in xrange(2, n) if check_prime_in_py(x)]py_time = timeit(stmt='get_prime_in_py(1000000)', setup='from __main__ import get_prime_in_py',         number=10)c_time = timeit(stmt='get_prime_in_c(1000000)', setup='from __main__ import get_prime_in_c',        number=10)print "Python version: {} seconds".format(py_time)print "C version: {} seconds".format(c_time)

輸出

Python version: 43.4539749622 secondsC version: 8.56250786781 seconds

我們可以看到很明顯的效能差距 這裡有更多的方法去判斷一個數是否是素數

再來看一個複雜點的例子 快速排序

mylib.c

#include <stdio.h>typedef struct _Range {  int start, end;} Range;Range new_Range(int s, int e) {  Range r;  r.start = s;  r.end = e;  return r;}void swap(int *x, int *y) {  int t = *x;  *x = *y;  *y = t;}void quick_sort(int arr[], const int len) {  if (len <= 0)    return;  Range r[len];  int p = 0;  r[p++] = new_Range(0, len - 1);  while (p) {    Range range = r[--p];    if (range.start >= range.end)      continue;    int mid = arr[range.end];    int left = range.start, right = range.end - 1;    while (left < right) {      while (arr[left] < mid && left < right)        left++;      while (arr[right] >= mid && left < right)        right--;      swap(&arr[left], &arr[right]);    }    if (arr[left] >= arr[range.end])      swap(&arr[left], &arr[range.end]);    else      left++;    r[p++] = new_Range(range.start, left - 1);    r[p++] = new_Range(left + 1, range.end);  }}
gcc -shared -o mylib.so -fPIC mylib.c

使用ctypes有一個麻煩點的地方是原生的C代碼使用的類型可能跟Python不能明確的對應上來。比如這裡什麼是Python中的數組?列表?還是 array 模組中的一個數組。所以我們需要進行轉換

test.py

import ctypesimport timeimport randomquick_sort = ctypes.CDLL('./mylib.so').quick_sortnums = []for _ in range(100):  r = [random.randrange(1, 100000000) for x in xrange(100000)]  arr = (ctypes.c_int * len(r))(*r)  nums.append((arr, len(r)))init = time.clock()for i in range(100):  quick_sort(nums[i][0], nums[i][1])print "%s" % (time.clock() - init)

輸出

1.874907

與Python list 的 sort 方法進行對比

import ctypesimport timeimport randomquick_sort = ctypes.CDLL('./mylib.so').quick_sortnums = []for _ in range(100):  nums.append([random.randrange(1, 100000000) for x in xrange(100000)])init = time.clock()for i in range(100):  nums[i].sort()print "%s" % (time.clock() - init)

輸出

2.501257

至於結構體,需要定義一個類,包含相應的欄位和類型

class Point(ctypes.Structure):  _fields_ = [('x', ctypes.c_double),        ('y', ctypes.c_double)]

除了匯入我們自己寫的C語言擴充檔案,我們還可以直接匯入系統提供的庫檔案,比如linux下c標準庫的實現 glibc

import timeimport randomfrom ctypes import cdlllibc = cdll.LoadLibrary('libc.so.6') # Linux系統# libc = cdll.msvcrt # Windows系統init = time.clock()randoms = [random.randrange(1, 100) for x in xrange(1000000)]print "Python version: %s seconds" % (time.clock() - init)init = time.clock()randoms = [(libc.rand() % 100) for x in xrange(1000000)]print "C version : %s seconds" % (time.clock() - init)

輸出

Python version: 0.850172 secondsC version : 0.27645 seconds

總結

以上就是這篇文章的全部內容,希望對大家學習或使用Python能有一定的協助,如果有疑問大家可以留言交流。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.