我编写了这个程序来正确学习如何使用多线程。我想在我自己的程序中实现类似的东西:
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会导致我的减速吗?
编辑2(2017-01-18):因此,在网上搜索相当多的东西之后,我觉得python对于并行性来说真的很糟糕。我试图做的是对在tensorflow中实现的神经网络中使用的python函数进行分析......似乎添加自定义操作是可行的方法。
答案 0 :(得分:0)
这里的问题数量非常多。执行太少工作的太多(系统!)线程,GIL等。这是我认为对Python中并行性的一个非常好的介绍:
https://www.youtube.com/watch?v=MCs5OvhV9S4
实时编码非常棒。