【发布时间】:2021-01-07 03:44:20
【问题描述】:
from concurrent.futures import ProcessPoolExecutor
from concurrent.futures import as_completed
import numpy as np
import time
#creating iterable
testDict = {}
for i in range(1000):
testDict[i] = np.random.randint(1,10)
#default method
stime = time.time()
newdict = []
for k, v in testDict.items():
for i in range(1000):
v = np.tanh(v)
newdict.append(v)
etime = time.time()
print(etime - stime)
#output: 1.1139910221099854
#multi processing
stime = time.time()
testresult = []
def f(item):
x = item[1]
for i in range(1000):
x = np.tanh(x)
return x
def main(testDict):
with ProcessPoolExecutor(max_workers = 8) as executor:
futures = [executor.submit(f, item) for item in testDict.items()]
for future in as_completed(futures):
testresult.append(future.result())
if __name__ == '__main__':
main(testDict)
etime = time.time()
print(etime - stime)
#output: 3.4509658813476562
学习多处理和测试的东西。进行测试以检查我是否正确实现了这一点。查看所花费的输出时间,并发方法慢了 3 倍。那怎么了?
我的目标是并行化一个脚本,该脚本主要在大约 500 个项目的字典上运行。每个循环,这 500 个项目的值都会被处理和更新。这个循环可以说是 5000 代。 k,v 对中没有一个与其他 k,v 对交互。 [它是一种遗传算法]。
我还在寻找有关如何并行化上述目标的指南。如果我在我的遗传算法代码中对我的每个函数使用正确的并发期货方法,其中每个函数接受字典的输入并输出一个新字典,它会有用吗?任何指南/资源/帮助表示赞赏。
编辑:如果我运行这个例子:https://docs.python.org/3/library/concurrent.futures.html#processpoolexecutor-example,它需要比默认的循环检查多 3 倍的时间来解决。
【问题讨论】:
-
您的机器上有多少个内核?如果将迭代次数从 1000 更改为 10000,您观察到的趋势是否会继续? 10万?您可能只是通过使用如此小的数据集来观察并行化开销。或者,如果您的内核少于 8 个,则可能只是 CPU 过载。
-
@SethMMorton 4 核。以 10000 跑并看到相同的 3 倍比率。 Overhead 是一种查询途径,但如果可以的话,请查看我对我的帖子所做的编辑:即使是文档示例的运行速度也比列表上的循环慢。
-
如果您只使用 4 个工人怎么办?您创建的进程似乎是核心的两倍。
-
由于某种原因恶化了。
标签: python multiprocessing concurrent.futures