前言
python作為一門腳本語言,其好處是語法簡單,很多東西都已經封裝好了,直接拿過來用就行,所以實現同樣一個功能,用Python寫要比用C/C++代碼量會少得多。但是優點也必然也伴隨著缺點(這是肯定的,不然還要其他語言干嘛),python最被人詬病的一個地方可能就是其運行速度了。這這是大部分腳本語言共同面對的問題,因為沒有編譯過程,直接逐行執行,所以要慢了一大截。所以在一些對速度要求很高的場合,一般都是使用C/C++這種編譯型語言來寫。但是很多時候,我們既想使用python的簡介優美,又不想損失太多的性能,這個時候有沒有辦法將python與C/C++結合到一起呢?這樣在性能與速度要求不高的地方,可以用pyhton寫,而關鍵的運算部分用C/C++寫,這樣就太好了。python在做科學計算或者數據分析時,這是一個非常普遍的需求。要想實現這個功能,python為我們提供了不止一種解決辦法。
下面我就逐一給大家介紹。
一、Cython 混合python與C
官方網址:http://docs.cython.org/en/latest/src/quickstart/overview.html。首先來看看cython的官方介紹吧。
[Cython] is a programming language that makes writing C extensions for the Python language as easy as Python itself. It aims to become a superset of the [Python]language which gives it high-level, object-oriented, functional, and dynamic programming. Its main feature on top of these is support for optional static type declarations as part of the language. The source code gets translated into optimized C/C++ code and compiled as Python extension modules. This allows for both very fast program execution and tight integration with external C libraries, while keeping up the high programmer productivity for which the Python language is well known.
簡單來說,cython就是一個內置了c數據類型的python,它是一個python的超集,兼容幾乎所有的純python代碼,但是又可以使用c的數據類型。這樣就可以同時使用c庫,又不失python的優雅。
好了,不講太多廢話,直接來看cython如何使用吧。這里的介紹大部分來自官網,由于cython涉及到的東西還比較多,所以這里只是簡單的入門介紹,詳細的信息請移步英文官網。
使用cython有兩種方式:第一個是編譯生成Python擴展文件(有點類似于dll,即動態鏈接庫),可以直接import使用。第二個是使用jupyter notebook或sage notebook 內聯 cython代碼。
先看第一種。還是舉最經典的hello world的例子吧。新建一個hello.pyx文件,定義一個hello函數如下:
def hello(name): print("Hello %s." % name)然后,我們來寫一個setup.py 文件(寫python擴展幾乎都要寫setup.py文件,我之前也簡單介紹過怎么寫)如下:
#!/usr/bin/env python# -*- coding: utf-8 -*-# @Time : 2017/5/8 9:09# @Author : Lyrichu# @Email : 919987476@qq.com# @File : setup.py'''@Description: setup.py for hello.pyx'''from Cython.Build import cythonizefrom distutils.core import setup# 編寫setup函數setup( name = "Hello", ext_modules = cythonize("hello.pyx"))            
新聞熱點
疑難解答