def random_walker(n: int, length: int) -> np.ndarray:
arr = np.zeros((n, length), dtype = float)
for i in range(n):
idx = 100
for j in range(length):
idx += idx*random.gauss(0.00015, 0.02)
arr[i, j] = idx
return arr
@njit
def nb_random_walker(n: int, length: int) -> np.ndarray:
arr = np.zeros((n, length), dtype = float)
for i in range(n):
idx = 100
for j in range(length):
idx += idx*random.gauss(0.00015, 0.02)
arr[i, j] = idx
return arr
我现在一个接一个地执行随机模拟运行,并计算两次运行的模拟持续时间。您可以在下面的代码中看到这一点。
# --- monte carlo run without numba ------------------
starttime = time.time()
arr = random_walker(10000, 365)
endtime = time.time()
print("monte carlo random walk without NUMBA: ")
print(endtime-starttime)
# --- monte carlo run with numba --------------------
starttime = time.time()
arr = nb_random_walker(10000, 365)
endtime = time.time()
print("monte carlo random walk with NUMBA: ")
print(endtime-starttime)
输出如下:
monte carlo random walk without NUMBA:
1.9181511402130127
monte carlo random walk with NUMBA:
0.6535243988037109
在这种情况下,
numba
将 monte-carlo 模拟运行时间几乎提高了
3 倍
。顺便说一下,这就是随机游走的样子:
Privacy Overview
This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.