多线程Python应用程序比单线程实现慢
我写这个程序是为了正确地学习如何使用多线程。我想在我自己的程序中实现类似的功能:多线程Python应用程序比单线程实现慢,python,multithreading,performance,python-multithreading,slowdown,Python,Multithreading,Performance,Python Multithreading,Slowdown,我写这个程序是为了正确地学习如何使用多线程。我想在我自己的程序中实现类似的功能: import numpy as np import time import os import math import random from threading import Thread def powExp(x, r): for c in range(x.shape[1]): x[r][c] = math.pow(100, x[r][c]) def main(): pri
import numpy as np
import time
import os
import math
import random
from threading import Thread
def powExp(x, r):
for c in range(x.shape[1]):
x[r][c] = math.pow(100, x[r][c])
def main():
print()
rows = 100
cols = 100
x = np.random.random((rows, cols))
y = x.copy()
start = time.time()
threads = []
for r in range(x.shape[0]):
t = Thread(target = powExp, args = (x, r))
threads.append(t)
t.start()
for t in threads:
t.join()
end = time.time()
print("Multithreaded calculation took {n} seconds!".format(n = end - start))
start = time.time()
for r in range(y.shape[0]):
for c in range(y.shape[1]):
y[r][c] = math.pow(100, y[r][c])
end = time.time()
print("Singlethreaded calculation took {n} seconds!".format(n = end - start))
print()
randRow = random.randint(0, rows - 1)
randCol = random.randint(0, cols - 1)
print("Checking random indices in x and y:")
print("x[{rR}][{rC}]: = {n}".format(rR = randRow, rC = randCol, n = x[randRow][randCol]))
print("y[{rR}][{rC}]: = {n}".format(rR = randRow, rC = randCol, n = y[randRow][randCol]))
print()
for r in range(x.shape[0]):
for c in range(x.shape[1]):
if(x[r][c] != y[r][c]):
print("ERROR NO WORK WAS DONE")
print("x[{r}][{c}]: {n} == y[{r}][{c}]: {ny}".format(
r = r,
c = c,
n = x[r][c],
ny = y[r][c]
))
quit()
assert(np.array_equal(x, y))
if __name__ == main():
main()
从代码中可以看出,这里的目标是通过为每列创建一个线程来并行化操作math.pow(100,x[r][c])。然而,这段代码非常慢,比单线程版本慢得多
输出:
Multithreaded calculation took 0.026447772979736328 seconds!
Singlethreaded calculation took 0.006798267364501953 seconds!
Checking random indices in x and y:
x[58][58]: = 9.792315687115973
y[58][58]: = 9.792315687115973
我搜索了stackoverflow,找到了一些关于GIL强制python字节码只能在单个内核上执行的信息。然而,我不确定这实际上是限制我并行化的原因。我尝试使用池而不是线程重新排列并行for循环。似乎什么都没用
编辑:此线程讨论相同的问题。由于GIL,在python中使用多线程来提高性能是完全不可能的吗?是GIL导致了我的减速吗
编辑2(2017-01-18):因此,从我在网上搜索了相当一段时间后收集到的信息来看,python对于并行性来说似乎真的很糟糕。我想做的是对tensorflow中实现的神经网络中使用的python函数进行并行化…似乎添加一个定制的op是一个不错的选择。这里的问题很多。。。很多的太多(System!)线程太少的工作,吉尔等。这就是我认为Python中的并行性的一个很好的介绍:
实时编码真是太棒了。可能是重复的,你知道你正在启动10000个线程吗?@KlausD。对不起,我错过了。我更新了代码和输出。尽管没有启动那么多线程,但仍然存在相同的问题!是的,GIL会影响你的表现。您不能将代码更改为使用多处理吗?在您发布之前,我更新了代码并输出。大量的线程被删除了!不过我会查看链接的,谢谢。