一行代碼讓 Python 的運行速度提高100倍
python一直被病垢運行速度太慢,但是實際上python的執(zhí)行效率并不慢,慢的是python用的解釋器Cpython運行效率太差。
“一行代碼讓python的運行速度提高100倍”這絕不是嘩眾取寵的論調。
我們來看一下這個最簡單的例子,從1一直累加到1億。
最原始的代碼:
import time def foo(x,y): tt = time.time() s = 0 for i in range(x,y): s += i print('Time used: {} sec'.format(time.time()-tt)) return s print(foo(1,100000000))
結果:
Time used: 6.779874801635742 sec
4999999950000000
我們來加一行代碼,再看看結果:
from numba import jit import time @jit def foo(x,y): tt = time.time() s = 0 for i in range(x,y): s += i print('Time used: {} sec'.format(time.time()-tt)) return s print(foo(1,100000000))
結果:
Time used: 0.04680037498474121 sec
4999999950000000
是不是快了100多倍呢?
那么下面就分享一下“為啥numba庫的jit模塊那么牛掰?”
NumPy的創(chuàng)始人Travis Oliphant在離開Enthought之后,創(chuàng)建了CONTINUUM,致力于將Python大數(shù)據(jù)處理方面的應用。最近推出的Numba項目能夠將處理NumPy數(shù)組的Python函數(shù)JIT編譯為機器碼執(zhí)行,從而上百倍的提高程序的運算速度。
Numba項目的主頁上有Linux下的詳細安裝步驟。編譯LLVM需要花一些時間。
Windows用戶可以從Unofficial Windows Binaries for Python Extension Packages下載安裝LLVMPy、meta和numba等幾個擴展庫。
下面我們看一個例子:
import numba as nb from numba import jit @jit('f8(f8[:])') def sum1d(array): s = 0.0 n = array.shape[0] for i in range(n): s += array[i] return s import numpy as np array = np.random.random(10000) %timeit sum1d(array) %timeit np.sum(array) %timeit sum(array) 10000 loops, best of 3: 38.9 us per loop 10000 loops, best of 3: 32.3 us per loop 100 loops, best of 3: 12.4 ms per loop
numba中提供了一些修飾器,它們可以將其修飾的函數(shù)JIT編譯成機器碼函數(shù),并返回一個可在Python中調用機器碼的包裝對象。為了能將Python函數(shù)編譯成能高速執(zhí)行的機器碼,我們需要告訴JIT編譯器函數(shù)的各個參數(shù)和返回值的類型。我們可以通過多種方式指定類型信息,在上面的例子中,類型信息由一個字符串'f8(f8[:])'指定。其中'f8'表示8個字節(jié)雙精度浮點數(shù),括號前面的'f8'表示返回值類型,括號里的表示參數(shù)類型,'[:]'表示一維數(shù)組。因此整個類型字符串表示sum1d()是一個參數(shù)為雙精度浮點數(shù)的一維數(shù)組,返回值是一個雙精度浮點數(shù)。
需要注意的是,JIT所產(chǎn)生的函數(shù)只能對指定的類型的參數(shù)進行運算:
print sum1d(np.ones(10, dtype=np.int32)) print sum1d(np.ones(10, dtype=np.float32)) print sum1d(np.ones(10, dtype=np.float64)) 1.2095376009e-312 1.46201599944e+185 10.0
如果希望JIT能針對所有類型的參數(shù)進行運算,可以使用autojit:
from numba import autojit @autojit def sum1d2(array): s = 0.0 n = array.shape[0] for i in range(n): s += array[i] return s %timeit sum1d2(array) print sum1d2(np.ones(10, dtype=np.int32)) print sum1d2(np.ones(10, dtype=np.float32)) print sum1d2(np.ones(10, dtype=np.float64)) 10000 loops, best of 3: 143 us per loop 10.0 10.0 10.0
autoit雖然可以根據(jù)參數(shù)類型動態(tài)地產(chǎn)生機器碼函數(shù),但是由于它需要每次檢查參數(shù)類型,因此計算速度也有所降低。numba的用法很簡單,基本上就是用jit和autojit這兩個修飾器,和一些類型對象。下面的程序列出numba所支持的所有類型:
print [obj for obj in nb.__dict__.values() if isinstance(obj, nb.minivect.minitypes.Type)] [size_t, Py_uintptr_t, uint16, complex128, float, complex256, void, int , long double, unsigned PY_LONG_LONG, uint32, complex256, complex64, object_, npy_intp, const char *, double, unsigned short, float, object_, float, uint64, uint32, uint8, complex128, uint16, int, int , uint8, complex64, int8, uint64, double, long double, int32, double, long double, char, long, unsigned char, PY_LONG_LONG, int64, int16, unsigned long, int8, int16, int32, unsigned int, short, int64, Py_ssize_t]
工作原理
numba的通過meta模塊解析Python函數(shù)的ast語法樹,對各個變量添加相應的類型信息。然后調用llvmpy生成機器碼,最后再生成機器碼的Python調用接口。
meta模塊
通過研究numba的工作原理,我們可以找到許多有用的工具。例如meta模塊可在程序源碼、ast語法樹以及Python二進制碼之間進行相互轉換。下面看一個例子:
def add2(a, b): return a + b
decompile_func能將函數(shù)的代碼對象反編譯成ast語法樹,而str_ast能直觀地顯示ast語法樹,使用這兩個工具學習Python的ast語法樹是很有幫助的。
from meta.decompiler import decompile_func from meta.asttools import str_ast print str_ast(decompile_func(add2)) FunctionDef(args=arguments(args=[Name(ctx=Param(), id='a'), Name(ctx=Param(), id='b')], defaults=[], kwarg=None, vararg=None), body=[Return(value=BinOp(left=Name(ctx=Load(), id='a'), op=Add(), right=Name(ctx=Load(), id='b')))], decorator_list=[], name='add2')
而python_source可以將ast語法樹轉換為Python源代碼:
from meta.asttools import python_source python_source(decompile_func(add2)) def add2(a, b): return (a + b)
decompile_pyc將上述二者結合起來,它能將Python編譯之后的pyc或者pyo文件反編譯成源代碼。下面我們先寫一個tmp.py文件,然后通過py_compile將其編譯成tmp.pyc。
with open("tmp.py", "w") as f: f.write(""" def square_sum(n): s = 0 for i in range(n): s += i**2 return s """) import py_compile py_compile.compile("tmp.py")
下面調用decompile_pyc將tmp.pyc顯示為源代碼:
with open("tmp.pyc", "rb") as f: decompile_pyc(f) def square_sum(n): s = 0 for i in range(n): s += (i ** 2) return s
llvmpy模塊
LLVM是一個動態(tài)編譯器,llvmpy則可以通過Python調用LLVM動態(tài)地創(chuàng)建機器碼。直接通過llvmpy創(chuàng)建機器碼是比較繁瑣的,例如下面的程序創(chuàng)建一個計算兩個整數(shù)之和的函數(shù),并調用它計算結果。
from llvm.core import Module, Type, Builder from llvm.ee import ExecutionEngine, GenericValue # Create a new module with a function implementing this: # # int add(int a, int b) { # return a + b; # } # my_module = Module.new('my_module') ty_int = Type.int() ty_func = Type.function(ty_int, [ty_int, ty_int]) f_add = my_module.add_function(ty_func, "add") f_add.args[0].name = "a" f_add.args[1].name = "b" bb = f_add.append_basic_block("entry") # IRBuilder for our basic block builder = Builder.new(bb) tmp = builder.add(f_add.args[0], f_add.args[1], "tmp") builder.ret(tmp) # Create an execution engine object. This will create a JIT compiler # on platforms that support it, or an interpreter otherwise ee = ExecutionEngine.new(my_module) # Each argument needs to be passed as a GenericValue object, which is a kind # of variant arg1 = GenericValue.int(ty_int, 100) arg2 = GenericValue.int(ty_int, 42) # Now let's compile and run! retval = ee.run_function(f_add, [arg1, arg2]) # The return value is also GenericValue. Let's print it. print "returned", retval.as_int() returned 142
f_add就是一個動態(tài)生成的機器碼函數(shù),我們可以把它想象成C語言編譯之后的函數(shù)。在上面的程序中,我們通過ee.run_function調用此函數(shù),而實際上我們還可以獲得它的地址,然后通過Python的ctypes模塊調用它。
首先通過ee.get_pointer_to_function獲得f_add函數(shù)的地址:
addr = ee.get_pointer_to_function(f_add) addr 2975997968L
然后通過ctypes.PYFUNCTYPE創(chuàng)建一個函數(shù)類型:
import ctypes f_type = ctypes.PYFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_int)
最后通過f_type將函數(shù)的地址轉換為可調用的Python函數(shù),并調用它:
f = f_type(addr) f(100, 42) 142
numba所完成的工作就是:
解析Python函數(shù)的ast語法樹并加以改造,添加類型信息;
將帶類型信息的ast語法樹通過llvmpy動態(tài)地轉換為機器碼函數(shù),然后再通過和ctypes類似的技術為機器碼函數(shù)創(chuàng)建包裝函數(shù)供Python調用。
總結
以上所述是小編給大家介紹的一行代碼讓 Python 的運行速度提高100倍,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關文章
python網(wǎng)絡編程學習筆記(五):socket的一些補充
前面已經(jīng)為大家介紹了python socket的一些相關知識,這里為大家補充下,方便需要的朋友2014-06-06Python Flask-Login實現(xiàn)用戶會話管理
這篇文章主要介紹了Python Flask-Login實現(xiàn)用戶會話管理過程,F(xiàn)lask-Login為Flask提供用戶會話管理。它處理登錄、注銷和長時間記住用戶會話等常見任務2022-12-12python pip安裝包出現(xiàn):Failed building wheel for xxx錯誤的解決
今天小編就為大家分享一篇python pip安裝包出現(xiàn):Failed building wheel for xxx錯誤的解決,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12用Python簡單實現(xiàn)個貪吃蛇小游戲(保姆級教程)
本文基于Windows環(huán)境開發(fā),適合Python新手,文中有非常詳細的代碼示例,對正在學習python的小伙伴們很有幫助,需要的朋友可以參考下2021-06-06