我正在尝试使用多处理运行一个简单的测试。在我导入 numpy 之前,测试运行良好(即使程序中没有使用它)。这是代码:
from multiprocessing import Pool
import time
import numpy as np #this is the problematic line
def CostlyFunc(N):
""""""
tstart = time.time()
x = 0
for i in xrange(N):
for j in xrange(N):
if i % 2: x += 2
else: x -= 2
print "CostlyFunc : elapsed time %f s" % (time.time() - tstart)
return x
#serial application
ResultList0 = []
StartTime = time.time()
for i in xrange(3):
ResultList0.append(CostlyFunc(5000))
print "Elapsed time (serial) : ", time.time() - StartTime
#multiprocessing application
StartTime = time.time()
pool = Pool()
asyncResult = pool.map_async(CostlyFunc, [5000, 5000, 5000])
ResultList1 = asyncResult.get()
print "Elapsed time (multiporcessing) : ", time.time() - StartTime
如果我不导入 numpy,结果是:
CostlyFunc : elapsed time 2.866265 s
CostlyFunc : elapsed time 2.793213 s
CostlyFunc : elapsed time 2.794936 s
Elapsed time (serial) : 8.45455098152
CostlyFunc : elapsed time 2.889815 s
CostlyFunc : elapsed time 2.891556 s
CostlyFunc : elapsed time 2.898898 s
Elapsed time (multiporcessing) : 2.91595196724
总经过时间类似于 1 个进程所需的时间,这意味着计算已并行化。如果我确实 import numpy ,结果将变为:
CostlyFunc : elapsed time 2.877116 s
CostlyFunc : elapsed time 2.866778 s
CostlyFunc : elapsed time 2.860894 s
Elapsed time (serial) : 8.60492110252
CostlyFunc : elapsed time 8.450145 s
CostlyFunc : elapsed time 8.473006 s
CostlyFunc : elapsed time 8.506402 s
Elapsed time (multiporcessing) : 8.55398178101
串行和多处理方法所用的总时间相同,因为只使用一个内核。很明显,问题来自 numpy. 我的多处理版本和 NumPy 版本之间是否可能不兼容?
我目前在 linux 上使用 Python2.7、NumPy 1.6.2 和 multiprocessing 0.70a1