并行python:只需运行函数n次 [英] parallel python: just run function n times

查看:141
本文介绍了并行python:只需运行函数n次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回多维numpy数组作为输出的python函数.这是一个带有随机数的蒙特卡洛模拟,我想用相同的输入运行此函数n次,收集数据并取平均值.有没有一种简单的方法可以使用multiprocessing来实现这一目标?

I have a python function that returns multi-dimensional numpy array as output. It's a Monte Carlo simulation with random numbers and I would like to run this function n times with the same input, collect the data and do the average. Is there a simple way to use multiprocessing to achieve this?

推荐答案

例如,使用4个过程使用简单平方函数计算平均值:

For example, calc average with simple square function using 4 processes:

from multiprocessing import Pool

def f(x):
    return x*x

if __name__ == '__main__':
    pool = Pool(processes=4)
    n = 10000000
    inputs = xrange(n)
    # calc f output using 4 processes
    out_list = pool.map(f, inputs)
    # average  
    print sum(out_list) / float(n)

这篇关于并行python:只需运行函数n次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆