嘿,我正在尝试运行一个简单的代码,使用并行 Python 同时将数字列表添加在一起
import sys, time
import pp
import numpy
x = numpy.arange(-20.0,20.0,0.5)
def function(raw_input):
f = 0
for i in numpy.arange(len(x)):
f+=1
a=raw_input[0]
b=raw_input[1]
c=raw_input[2]
d=raw_input[3]
print len(x)
return (a+b+c+d)+f
# tuple of all parallel python servers to connect with
ppservers = ()
#ppservers = ("10.0.0.1",)
if len(sys.argv) > 1:
ncpus = int(sys.argv[1])
# Creates jobserver with ncpus workers
job_server = pp.Server(ncpus, ppservers=ppservers)
else:
# Creates jobserver with automatically detected number of workers
job_server = pp.Server(ppservers=ppservers)
print "Starting pp with", job_server.get_ncpus(), "workers"
start_time = time.time()
# The following submits 4 jobs and then retrieves the results
puts = ([1,2,3,4], [3,2,3,4],[4,2,3,6],[2,3,4,5])
jobs = [(raw_input, job_server.submit(function,(raw_input,), (), ("numpy",))) for raw_input in puts]
for raw_input, job in jobs:
print "Sum of numbers", raw_input, "is", job()
print "Time elapsed: ", time.time() - start_time, "s"
job_server.print_stats()
所以基本上我希望它在添加 [3,2,3,4],[4,2,3,6],[2,3 的同时将 [1,2,3,4] 添加在一起,4,5]。并将 x 的长度(即 80)添加到所有答案中。 输出应如下所示:
从 4 名 worker 开始 pp
数字 [1, 2, 3, 4] 的总和为 90
数字 [3, 2, 3, 4] 的总和为 92
数字 [4, 2, 3, 6] 的总和为 95
数字 [2, 3, 4, 5] 的总和为 94
已用时间:0.394000053406 秒
作业执行统计:
工作数量 |占所有职位的百分比 |工作时间总和 |每份工作的时间|作业服务器
4 | 100.00 | 1.4380 | 0.359500 | local
自服务器创建以来耗时 0.442999839783
我遇到的问题是,当 x 在“函数”之外时,shell 返回时全局名称“x”未定义,但如果将 x 放入 shell 中,它会返回 x 的完整数组。
我很困惑,为什么当我将它放入 shell 中时,它的定义足够明确,可以返回“x”,但该作业找不到 x 或函数定义之外的任何其他内容。
最佳答案
我认为问题在于 x 是在作业服务器(即在 shell 中运行的服务器)上定义的,而不是在作业工作人员中定义的,因为工作人员只能访问其输入中的变量。
您应该能够通过在提交作业时传入 x 作为附加参数来修复此问题。
据我所知,f 的计算始终会得到 len(x) 的结果,因此您可以简单地传入 f 的值:
import sys, time
import pp
import numpy
x = numpy.arange(-20.0,20.0,0.5)
def function(raw_input,f):
a=raw_input[0]
b=raw_input[1]
c=raw_input[2]
d=raw_input[3]
return (a+b+c+d)+f
# tuple of all parallel python servers to connect with
ppservers = ()
#ppservers = ("10.0.0.1",)
if len(sys.argv) > 1:
ncpus = int(sys.argv[1])
# Creates jobserver with ncpus workers
job_server = pp.Server(ncpus, ppservers=ppservers)
else:
# Creates jobserver with automatically detected number of workers
job_server = pp.Server(ppservers=ppservers)
print "Starting pp with", job_server.get_ncpus(), "workers"
start_time = time.time()
# The following submits 4 jobs and then retrieves the results
puts = ([1,2,3,4], [3,2,3,4],[4,2,3,6],[2,3,4,5])
jobs = [(raw_input, job_server.submit(function,(raw_input,len(x)), (), ("numpy",))) for raw_input in puts]
for raw_input, job in jobs:
print "Sum of numbers", raw_input, "is", job()
print "Time elapsed: ", time.time() - start_time, "s"
job_server.print_stats()
关于python - 并行Python全局名称错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9282827/