
David
Beazley在PyCon
2010上发表了关于此问题的演讲。正如其他人已经指出的那样,对于某些任务,尤其是对多核使用线程可能会导致性能比单线程执行的同一任务慢。Beazley发现,问题与多个内核发生了“
GIL之战”有关:
为避免GIL争用,让任务在单独的进程而不是单独的线程中运行可能会获得更好的结果。在多处理模块提供了一个方便的方式来做到这一点特别是因为多处理API是非常相似的线程API。
import multiprocessing as mpimport datetime as dtdef work(): t = dt.datetime.now() print mp.current_process().name, t i = 0 while i < 100000000: i+=1 t2 = dt.datetime.now() print mp.current_process().name, t2, t2-tif __name__ == '__main__': print "single process:" t1 = mp.Process(target=work) t1.start() t1.join() print "multi process:" t1 = mp.Process(target=work) t1.start() t2 = mp.Process(target=work) t2.start() t1.join() t2.join()
产量
single process:Process-1 2011-12-06 12:34:20.611526Process-1 2011-12-06 12:34:28.494831 0:00:07.883305multi process:Process-3 2011-12-06 12:34:28.497895Process-2 2011-12-06 12:34:28.503433Process-2 2011-12-06 12:34:36.458354 0:00:07.954921Process-3 2011-12-06 12:34:36.546656 0:00:08.048761
PS。正如zeekay在评论中指出的那样,GIL之战仅对CPU密集型任务而言是严峻的。对于IO绑定的任务来说应该不是问题。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)