3

我有数以万计的模拟要在具有多个内核的系统上运行。目前,它是串行完成的,我知道我的输入参数,并将我的结果存储在一个字典中。

系列版本

import time
import random

class MyModel(object):
    input = None
    output = None

    def run(self):
        time.sleep(random.random())  # simulate a complex task
        self.output = self.input * 10


# Run serial tasks and store results for each parameter

parameters = range(10)
results = {}

for p in parameters:
    m = MyModel()
    m.input = p
    m.run()
    results[p] = m.output

print('results: ' + str(results))

这需要 <10 秒,并显示正确的结果:

results: {0: 0, 1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60, 7: 70, 8: 80, 9: 90}

并行版本

我尝试并行化此过程是基于multiprocessing文本“一个示例显示如何使用队列将任务提供给工作进程集合并收集结果”附近的模块中的示例(抱歉,没有可用的 URL 锚点)。

以下构建在串行版本的上半部分:

from multiprocessing import Process, Queue
NUMBER_OF_PROCESSES = 4

def worker(input, output):
    for args in iter(input.get, 'STOP'):
        m = MyModel()
        m.input = args[0]
        m.run()
        output.put(m.output)


# Run parallel tasks and store results for each parameter

parameters = range(10)
results = {}

# Create queues
task_queue = Queue()
done_queue = Queue()

# Submit tasks
tasks = [(t,) for t in parameters]
for task in tasks:
    task_queue.put(task)

# Start worker processes
for i in range(NUMBER_OF_PROCESSES):
    Process(target=worker, args=(task_queue, done_queue)).start()

# Get unordered results
for i in range(len(tasks)):
    results[i] = done_queue.get()

# Tell child processes to stop
for i in range(NUMBER_OF_PROCESSES):
    task_queue.put('STOP')

print('results: ' + str(results))

现在只需要几秒钟,但输入和结果之间的映射顺序是混乱的。

results: {0: 10, 1: 0, 2: 60, 3: 40, 4: 20, 5: 80, 6: 30, 7: 90, 8: 70, 9: 50}

我意识到我正在results基于 unordered填充done_queue.get(),但我不确定如何正确映射到task_queue. 有任何想法吗?还有其他方法可以使这个更清洁吗?

4

1 回答 1

1

啊哈!worker需要嵌入某种ID,比如用来返回输出队列的输入参数,可以用来标识返回的进程。以下是所需的修改:

def worker(input, output):
    for args in iter(input.get, 'STOP'):
        m = MyModel()
        m.input = args[0]
        m.run()
        # Return a tuple of an ID (the input parameter), and the model output
        return_obj = (m.input, m.output)
        output.put(return_obj)

# Get unordered results
for i in range(len(tasks)):
    # Unravel output tuple, which has the input parameter 'p' used as an ID
    p, result = done_queue.get()
    results[p] = result
于 2013-07-04T06:32:49.140 回答