我目前正在使用 dispy 执行 10 个随机数的阶乘计算,它将任务“分发”到各个节点。但是,如果其中一个计算是大量的阶乘,比如说factorial(100),那么如果该任务需要很长时间,但 dispy仅在单个节点上运行它。
我如何确保 dispy 分解并将此任务分发到其他节点,以便它不会花费太多时间?
这是我到目前为止提出的代码,其中计算了 10 个随机数的阶乘,而第 5 次计算始终是阶乘(100):-
# 'compute' is distributed to each node running 'dispynode'
def compute(n):
import time, socket
ans = 1
for i in range(1,n+1):
ans = ans * i
time.sleep(n)
host = socket.gethostname()
return (host, n,ans)
if __name__ == '__main__':
import dispy, random
cluster = dispy.JobCluster(compute)
jobs = []
for i in range(10):
# schedule execution of 'compute' on a node (running 'dispynode')
# with a parameter (random number in this case)
if(i==5):
job = cluster.submit(100)
else:
job = cluster.submit(random.randint(5,20))
job.id = i # optionally associate an ID to job (if needed later)
jobs.append(job)
# cluster.wait() # waits for all scheduled jobs to finish
for job in jobs:
host, n, ans = job() # waits for job to finish and returns results
print('%s executed job %s at %s with %s as input and %s as output' % (host, job.id, job.start_time, n,ans))
# other fields of 'job' that may be useful:
# print(job.stdout, job.stderr, job.exception, job.ip_addr, job.start_time, job.end_time)
cluster.print_status()