我能够让这个在我自己的测试中工作。
我的代码基于此链接:https://aws.amazon.com/blogs/compute/parallel-processing-in-python-with-aws-lambda/ https://aws.amazon.com/blogs/compute/parallel-processing-in-python-with-aws-lambda/
注1:你必须增加 lambda 函数的内存分配。使用默认的最小数量,多处理不会提高性能。我的帐户可以分配的最大数量(3008MB)达到了以下数字。
NB2:我在这里完全忽略了最大并行进程。我的用法没有太多需要处理的元素。
使用下面的代码,用法是:
work = funcmap(yourfunction,listofstufftoworkon)
yourresults = work.run()
从我的笔记本电脑运行:
jumper@jumperdebian[3333] ~/scripts/tmp 2019-09-04 11:52:30
└─ $ ∙ python3 -c "import tst; tst.lambda_handler(None,None)"
results : [(35, 9227465), (35, 9227465), (35, 9227465), (35, 9227465)]
SP runtime : 9.574460506439209
results : [(35, 9227465), (35, 9227465), (35, 9227465), (35, 9227465)]
MP runtime : 6.422513484954834
从AWS运行:
Function Logs:
START RequestId: 075a92c0-7c4f-4f48-9820-f394ee899a97 Version: $LATEST
results : [(35, 9227465), (35, 9227465), (35, 9227465), (35, 9227465)]
SP runtime : 12.135798215866089
results : [(35, 9227465), (35, 9227465), (35, 9227465), (35, 9227465)]
MP runtime : 7.293526887893677
END RequestId: 075a92c0-7c4f-4f48-9820-f394ee899a97
这是测试代码:
import time
from multiprocessing import Process, Pipe
import boto3
class funcmap(object):
fmfunction=None
fmlist=None
def __init__(self,pfunction,plist):
self.fmfunction=pfunction
self.fmlist=plist
def calculation(self, pfunction, pload, conn):
panswer=pfunction(pload)
conn.send([pload,panswer])
conn.close()
def run(self):
datalist = self.fmlist
processes = []
parent_connections = []
for datum in datalist:
parent_conn, child_conn = Pipe()
parent_connections.append(parent_conn)
process = Process(target=self.calculation, args=(self.fmfunction, datum, child_conn,))
processes.append(process)
pstart=time.time()
for process in processes:
process.start()
#print("starting at t+ {} s".format(time.time()-pstart))
for process in processes:
process.join()
#print("joining at t+ {} s".format(time.time()-pstart))
results = []
for parent_connection in parent_connections:
resp=parent_connection.recv()
results.append((resp[0],resp[1]))
return results
def fibo(n):
if n <= 2 : return 1
return fibo(n-1)+fibo(n-2)
def lambda_handler(event, context):
#worklist=[22,23,24,25,26,27,28,29,30,31,32,31,30,29,28,27,26,27,28,29]
#worklist=[22,23,24,25,26,27,28,29,30]
worklist=[30,30,30,30]
#worklist=[30]
_start = time.time()
results=[]
for a in worklist:
results.append((a,fibo(a)))
print("results : {}".format(results))
_end = time.time()
print("SP runtime : {}".format(_end-_start))
_mstart = time.time()
work = funcmap(fibo,worklist)
results = work.run()
print("results : {}".format(results))
_mend = time.time()
print("MP runtime : {}".format(_mend-_mstart))
希望能帮助到你。