线程中的只读 numpy 数组 python
read-only numpy array in threading python
我有多个使用 numpy 数组的线程。
import threading
import numpy as np
import time
shared_array = np.ones((5, 5))
def run(shared_array, nb_iters):
k = shared_array**2
for i in range(nb_iters):
k+=2
def multi_thread():
jobs = []
for _ in range(5):
thread = threading.Thread(target=run, args=(shared_array, 1000000))
jobs.append(thread)
for j in jobs:
j.start()
for j in jobs:
j.join()
t0 = time.time()
multi_thread()
print(time.time() - t0)
#result: 6.502177000045776
t0 = time.time()
# we used 1000000 iterations for each thread => total nb of iterations = 5 * 1000000
run(shared_array, 1000000 * 5)
print(time.time() - t0)
#result: 6.6372435092926025
问题是添加numpy数组作为参数后,5个并行线程的执行时间等于顺序执行!
所以我想知道如何使一个程序(类似于这个)并行,
这是一个糟糕的例子。 Python 有一个内部锁(全局解释器锁,GIL),这意味着一次只有一个线程可以执行 Python 代码。当你进入 numpy 时,它可以 运行 并行,但是因为你的数组太小了,你几乎没有花时间在 numpy 上,所以你没有任何并行性可言。
我有多个使用 numpy 数组的线程。
import threading
import numpy as np
import time
shared_array = np.ones((5, 5))
def run(shared_array, nb_iters):
k = shared_array**2
for i in range(nb_iters):
k+=2
def multi_thread():
jobs = []
for _ in range(5):
thread = threading.Thread(target=run, args=(shared_array, 1000000))
jobs.append(thread)
for j in jobs:
j.start()
for j in jobs:
j.join()
t0 = time.time()
multi_thread()
print(time.time() - t0)
#result: 6.502177000045776
t0 = time.time()
# we used 1000000 iterations for each thread => total nb of iterations = 5 * 1000000
run(shared_array, 1000000 * 5)
print(time.time() - t0)
#result: 6.6372435092926025
问题是添加numpy数组作为参数后,5个并行线程的执行时间等于顺序执行!
所以我想知道如何使一个程序(类似于这个)并行,
这是一个糟糕的例子。 Python 有一个内部锁(全局解释器锁,GIL),这意味着一次只有一个线程可以执行 Python 代码。当你进入 numpy 时,它可以 运行 并行,但是因为你的数组太小了,你几乎没有花时间在 numpy 上,所以你没有任何并行性可言。