我發現我的模擬瓶頸之一是從泊松分佈產生的隨機數。我原來的代碼是這樣的Numba和隨機數從泊松分佈
import numpy as np
#Generating some data. In the actual code this comes from the previous
#steps in the simulation. But this gives an example of the type of data
n = 5000000
pop_n = np.array([range(500000)])
pop_n[:] = np.random.poisson(lam=n*pop_n/np.sum(pop_n))
現在,我讀到numba可以非常簡單地提高速度。我定義了功能
from numba import jit
@jit()
def poisson(n, pop_n, np=np):
return np.random.poisson(lam=n*pop_n/np.sum(pop_n))
這個確實運行得比原來快。不過,我嘗試走得更遠:)當我寫
@jit(nopython=True)
def poisson(n, pop_n, np=np):
return np.random.poisson(lam=n*pop_n/np.sum(pop_n))
我
Failed at nopython (nopython frontend)
Invalid usage of Function(np.random.poisson) with parameters (array(float64, 1d, C))
Known signatures:
* (float64,) -> int64
*() -> int64
* parameterized
一些問題:爲什麼是這樣的錯誤發生,如何解決它。
有更好的優化嗎?
看起來Numba還不支持從任何np.random函數返回數組。您應該首先設置一個指定其項目類型的空數組,然後才能添加值。看看這裏的例子https://github.com/numba/numba/issues/1596 –
我沒有看到任何實際的原因,爲什麼這個功能應該更快。 'np.random.poisson'已經在C中實現了。在另一個編譯函數中包裝它最多會被編譯器優化,最壞的情況是會導致開銷。 – kazemakase
@kazemakase pop_n上的操作怎麼樣?它的數組除以它的總和? –