python加速包numba並行計算多線程

一、下面直接上代碼須要注意的地方numba的官網找到

  1)有一些坑本身去numba的官網找找看,下面是個人寫的一個加速的程序,但願對你有幫助。

#coding:utf-8
import time

from numba import jit, prange, vectorize
from numba import cuda
from numba import njit
import numpy as np


def adds(x,y,m):
    return [x*i for i in range(y)]

@jit(parallel=True,nogil=True)
# @njit(parallel=True,nogil=True)
def adds1(x,y,m):
    sd =  np.empty((y))
    for i in prange(y):
        for j in range(m):
            sd[i]=x*i*m
    return sd

@jit(parallel=True,nogil=True)
def test(n):
    temp = np.empty((50, 50)) # <--- allocation is hoisted as a loop invariant as `np.empty` is considered pure
    for i in prange(n):
        temp[:] = 0           # <--- this remains as assignment is a side effect
        for j in range(50):
            temp[j, j] = i
    return temp

if __name__=="__main__":
    n = 50
    max = 10000**2*12
    m=100
    # st1 = time.time()
    # val_1 = adds(n,max,m)
    # print(time.time()-st1)

    st2 = time.time()
    val_2 = adds1(n,max,m)
    print(time.time()-st2)

    st3 = time.time()
    tmp = test(100**3*10)
    print(time.time()-st3)

  2) 最後一個顯示時間輸入,

  若是不調用jit裝飾器的話這兩個程序在個人電腦直接跑不下來。調用事後,Python能夠作並行計算,開啓多線程,忽略gil動態鎖。多線程

相關文章
相關標籤/搜索