python - multiprocessing.Pool.map() 有效,但 Pool.apply() 无效
问题描述
我有以下代码用于并行计算查找图中节点之间的最短路径长度。
出于某种原因, pool.map() 有效,但 pool.apply() 无效。
你能帮我解决问题吗?
import multiprocessing as mp
import time
import networkx as nx
G = nx.fast_gnp_random_graph(2000, 0.001)
# Single core
current_time = time.time()
lengths = [nx.single_source_shortest_path_length(G, node) for node in G.nodes]
time_consumed = time.time() - current_time
print('single core time: %s' % time_consumed)
# pool map
def spl(node):
return nx.single_source_shortest_path_length(G, node)
pool = mp.Pool(mp.cpu_count())
current_time = time.time()
results = pool.map(spl, G.nodes)
time_consumed = time.time() - current_time
pool.close()
print('pool map %s core time: %s' % (mp.cpu_count(), time_consumed))
# Pool apply
pool = mp.Pool(mp.cpu_count())
current_time = time.time()
results = [pool.apply(spl, args=(node,)) for node in G.nodes]
time_consumed = time.time() - current_time
pool.close()
print('pool apply %s core time: %s' % (mp.cpu_count(), time_consumed))
输出:
single core time: 25.18528151512146
pool map 12 core time: 5.043155670166016
pool apply 12 core time: 29.906842470169067
解决方案
推荐阅读
- python - 可以导入pytorch但不能导入torch
- angular - Angular 2方式绑定组件
- python - 使用 Selenium 和 Python 从 svg 标签中的 g 标签获取文本
- javascript - 在evennode.com的真实主机上使用mongodb的问题
- excel - 如何改进将 14 列月薪表转换为 4 列数据集的 VBA 代码
- javascript - 如何在 DeviceMotionEvent javascript 中设置间隔
- sqlite - 如何将片假名添加到 SQLite3?
- unity3d - 如何更改 Vuforia AnchorInputListenerBehaviour?
- javascript - 单击按钮时如何更改按钮的背景颜色
- java - 在 Angular 站点中,即使 xpath 正确,元素也无法找到错误显示。尝试使用 javascript 执行器仍然无法正常工作