1. 臥槽!一行代碼讓 Python 的運行速度提高100倍

        共 6436字,需瀏覽 13分鐘

         ·

        2021-01-18 12:41


        來源:python寶典 ?鏈接:

        https://mp.weixin.qq.com/s/Vm0BKSljCzMMgRmIBbpxdQ

        python一直被病垢運行速度太慢,但是實際上python的執(zhí)行效率并不慢,慢的是python用的解釋器Cpython運行效率太差。

        “一行代碼讓python的運行速度提高100倍”這絕不是嘩眾取寵的論調(diào)。

        我們來看一下這個最簡單的例子,從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))

        結(jié)果:

        Time?used:?6.779874801635742?sec
        4999999950000000

        我們來加一行代碼,再看看結(jié)果:

        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))

        結(jié)果:

        Time?used:?0.04680037498474121?sec
        4999999950000000

        是不是快了100多倍呢?

        那么下面就分享一下“為啥numba庫的jit模塊那么牛掰?”

        NumPy的創(chuàng)始人Travis Oliphant在離開Enthought之后,創(chuàng)建了CONTINUUM,致力于將Python大數(shù)據(jù)處理方面的應(yīng)用。最近推出的Numba項目能夠?qū)⑻幚鞱umPy數(shù)組的Python函數(shù)JIT編譯為機(jī)器碼執(zhí)行,從而上百倍的提高程序的運算速度。

        Numba項目的主頁上有Linux下的詳細(xì)安裝步驟。編譯LLVM需要花一些時間。
        Windows用戶可以從Unofficial Windows Binaries for Python Extension Packages下載安裝LLVMPy、meta和numba等幾個擴(kuò)展庫。

        下面我們看一個例子:

        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編譯成機(jī)器碼函數(shù),并返回一個可在Python中調(diào)用機(jī)器碼的包裝對象。為了能將Python函數(shù)編譯成能高速執(zhí)行的機(jī)器碼,我們需要告訴JIT編譯器函數(shù)的各個參數(shù)和返回值的類型。我們可以通過多種方式指定類型信息,在上面的例子中,類型信息由一個字符串’f8(f8[:])’指定。其中’f8’表示8個字節(jié)雙精度浮點數(shù),括號前面的’f8’表示返回值類型,括號里的表示參數(shù)類型,’[:]’表示一維數(shù)組。因此整個類型字符串表示sum1d()是一個參數(shù)為雙精度浮點數(shù)的一維數(shù)組,返回值是一個雙精度浮點數(shù)。
        需要注意的是,JIT所產(chǎn)生的函數(shù)只能對指定的類型的參數(shù)進(jìn)行運算:

        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ù)進(jìn)行運算,可以使用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)生機(jī)器碼函數(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語法樹,對各個變量添加相應(yīng)的類型信息。然后調(diào)用llvmpy生成機(jī)器碼,最后再生成機(jī)器碼的Python調(diào)用接口。

        meta模塊

        通過研究numba的工作原理,我們可以找到許多有用的工具。例如meta模塊可在程序源碼、ast語法樹以及Python二進(jìn)制碼之間進(jìn)行相互轉(zhuǎn)換。下面看一個例子:

        def?add2(a,?b):
        ????return?a?+?b

        decompile_func能將函數(shù)的代碼對象反編譯成ast語法樹,而str_ast能直觀地顯示ast語法樹,使用這兩個工具學(xué)習(xí)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語法樹轉(zhuǎn)換為Python源代碼:

        from?meta.asttools?import?python_source
        python_source(decompile_func(add2))
        def?add2(a,?b):
        ????return?(a?+?b)

        decompile_pyc將上述二者結(jié)合起來,它能將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")

        下面調(diào)用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調(diào)用LLVM動態(tài)地創(chuàng)建機(jī)器碼。直接通過llvmpy創(chuàng)建機(jī)器碼是比較繁瑣的,例如下面的程序創(chuàng)建一個計算兩個整數(shù)之和的函數(shù),并調(diào)用它計算結(jié)果。

        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)生成的機(jī)器碼函數(shù),我們可以把它想象成C語言編譯之后的函數(shù)。在上面的程序中,我們通過ee.run_function調(diào)用此函數(shù),而實際上我們還可以獲得它的地址,然后通過Python的ctypes模塊調(diào)用它。
        首先通過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ù)的地址轉(zhuǎn)換為可調(diào)用的Python函數(shù),并調(diào)用它:

        f?=?f_type(addr)
        f(100,?42)
        142

        numba所完成的工作就是:
        解析Python函數(shù)的ast語法樹并加以改造,添加類型信息;
        將帶類型信息的ast語法樹通過llvmpy動態(tài)地轉(zhuǎn)換為機(jī)器碼函數(shù),然后再通過和ctypes類似的技術(shù)為機(jī)器碼函數(shù)創(chuàng)建包裝函數(shù)供Python調(diào)用。

        戀習(xí)Python

        關(guān)注戀習(xí)Python,Python都好練
        好文章,我在看??
        瀏覽 20
        點贊
        評論
        收藏
        分享

        手機(jī)掃一掃分享

        分享
        舉報
        評論
        圖片
        表情
        推薦
        點贊
        評論
        收藏
        分享

        手機(jī)掃一掃分享

        分享
        舉報
          
          

            1. 国产精品99久 | 无马视频 | 美女搞基网站在线观看 | 麻豆导航 | 东京热在线免费观看 |