【发布时间】:2017-05-31 06:48:18
【问题描述】:
我编写这个程序是为了正确学习如何使用多线程。我想在我自己的程序中实现类似的东西:
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 循环。似乎没有任何工作。
Python code performance decreases with threading
编辑:该主题讨论了同样的问题。由于 GIL,在 python 中使用多线程来提高性能是完全不可能的吗? GIL 是否导致我的速度变慢?
EDIT 2 (2017-01-18): 所以从我在网上搜索了很多后收集到的信息来看,python 似乎真的不适合并行性。我正在尝试做的是并行化在 tensorflow 中实现的神经网络中使用的 python 函数......似乎添加自定义操作是要走的路。
【问题讨论】:
-
您知道您正在启动 10,000 个线程吗?
-
@KlausD。对不起,我错过了。我更新了代码和输出。尽管没有启动那么多可笑的线程,但仍然有同样的问题!
-
是的,GIL 会影响你的表现。你不能改变你的代码来使用多处理吗?
标签: python multithreading performance python-multithreading slowdown