python多处理无法正常工作?

时间:2015-11-30 16:39:12

标签: python parallel-processing multiprocessing python-multiprocessing

代码:

import multiprocessing as mp
import time

def seq(count):
    print "runing seq"
    start_time = time.time()
    result = []
    for i in range(count):
        result.append(cube(i))
    print "seq --- time:{0:.4f}".format(time.time() - start_time)
    #print "seq --- time:{0:.4f}, result:{1}".format(time.time() - start_time, result)

def par(count):
    print "runing par"
    start_time = time.time()
    result = mp.Pool(processes=2).map(cube,range(count))
    print "par --- time:{0:.4f}".format(time.time() - start_time)
    #print "par --- time:{0:.4f}, result:{1}".format(time.time() - start_time, result)

def cube(x):
    return x*x*x


count = 4000000
seq(count)
par(count)

输出:

  

seq ---时间:1.7011

     

par ---时间:2.3112

我的mac为每个物理核心提供一个处理器,两个物理核心和2个虚拟核心。所以,我认为它应该可以并行运行以获得一些加速。但是,从输出中可以看出,并行版本比顺序版本慢。为什么会这样?

规格:

spec 4 virtual cores

1 个答案:

答案 0 :(得分:4)

问题在于您并行化的操作并不是非常昂贵,这会抵消multiprocessing的好处。使用time.sleep会带来一些开销;启动子进程并将数据从父进程移动到这些子进程需要花费很多时间(特别是与线程解决方案相比)。如果您在后台进程中所做的实际工作非常少,那么在进程之间移动数据的开销实际上最终会大于通过并行化工作节省的时间。

如果在测试代码中添加一个简短的import multiprocessing as mp import time def seq(count): print "runing seq" start_time = time.time() result = [] for i in range(count): result.append(cube(i)) print "seq --- time:{0:.4f}".format(time.time() - start_time) #print "seq --- time:{0:.4f}, result:{1}".format(time.time() - start_time, result) def par(count): print "runing par" start_time = time.time() result = mp.Pool(processes=2).map(cube,range(count)) print "par --- time:{0:.4f}".format(time.time() - start_time) #print "par --- time:{0:.4f}, result:{1}".format(time.time() - start_time, result) def cube(x): time.sleep(.01) return x*x*x if __name__ == "__main__": count = 400 seq(count) par(count) (并减少运行次数,那么你就不会永远等待),你可以更清楚地看到这一点:

runing seq
seq --- time:4.0488
runing par
par --- time:2.0408

输出:

cube

public function handle($request, Closure $next) { if ($this->auth->guest()) { if ($request->ajax()) { return response('Unauthorized.', 401); } else { return redirect()->guest('auth/login'); } } elseif (!\Auth::user()->is_activated()) { \Session::flash('message', 'Please activate your account to proceed.'); return redirect()->guest('/notice/activate'); } return $next($request); } 内花费的额外时间使得并行版本比顺序版本快两倍,这与预期的性能改进是正确的。