简体   繁体   English

并行化python中的函数调用

[英]Parallelizing a function call in python

I have a function in python which I need to execute it multiple times and at the same time (to save computational cost). 我在python中有一个函数,我需要同时执行多次(以节省计算成本)。 The following is a simple example and I don't know how to call my function at the same time! 以下是一个简单的示例,我不知道如何同时调用我的函数!

def f(x):
    return x

y1=f(x1)
y2=f(x2)

I need to execute y1 and y2 at the same time and wait until both finish and save the results. 我需要同时执行y1和y2,然后等到两者都完成并保存结果。 Thank you all in advance. 谢谢大家。

I would encourage you to read the https://docs.python.org/3/library/multiprocessing.html documentation, which has a great example. 我鼓励您阅读https://docs.python.org/3/library/multiprocessing.html文档,其中有一个很好的例子。 If you're using Python 3.x 如果您使用的是Python 3.x

from multiprocessing import Pool
def f(x):
    return x*x

if __name__ == '__main__':
    with Pool(5) as p:
        print(p.map(f, [1, 2, 3]))

If you're using python 2.7: https://docs.python.org/2.7/library/multiprocessing.html 如果您使用的是python 2.7: https//docs.python.org/2.7/library/multiprocessing.html

from multiprocessing import Pool

def f(x):
    return x*x

if __name__ == '__main__':
    p = Pool(5)
    print(p.map(f, [1, 2, 3]))

Another solution that might help you: 可能会帮助您的另一种解决方案:

import Queue
import threading

# your function with a slight change:
def f(q,x):
    q.put(x)

inputs = [1,2,3,4]

# aggregate to a queue:
q = Queue.Queue()

for x in inputs:
    t = threading.Thread(target=f, args=(q,x))
    t.daemon = True
    t.start()

outputs = q.get()
print outputs

output: 1 输出1

Here q holds the return value of f . q在这里保存f的返回值。

In any case I suggest you try and read this . 无论如何,我建议您尝试阅读此内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM