假设foo1
or foo2
受 CPU 限制,线程不会提高执行时间...事实上,它通常会使情况变得更糟...有关更多信息,请参阅David Beazley 在 PyCon2010 上关于全局解释器锁的演讲 http://python.mirocommunity.org/video/1479/pycon-2010-understanding-the-p / Pycon2010 GIL 幻灯片 http://www.dabeaz.com/python/UnderstandingGIL.pdf。本演示内容非常丰富,我强烈推荐给任何尝试在 CPU 核心之间分配负载的人。
提高性能的最佳方法是多处理模块 http://docs.python.org/library/multiprocessing.html
假设之间不需要共享状态foo1()
and foo2()
,这样做是为了提高执行性能......
from multiprocessing import Process, Queue
import time
def foo1(queue, arg1):
# Measure execution time and return the total time in the queue
print "Got arg1=%s" % arg1
start = time.time()
while (arg1 > 0):
arg1 = arg1 - 1
time.sleep(0.01)
# return the output of the call through the Queue
queue.put(time.time() - start)
def foo2(queue, arg1):
foo1(queue, 2*arg1)
_start = time.time()
my_q1 = Queue()
my_q2 = Queue()
# The equivalent of x = foo1(50) in OP's code
p1 = Process(target=foo1, args=[my_q1, 50])
# The equivalent of y = foo2(50) in OP's code
p2 = Process(target=foo2, args=[my_q2, 50])
p1.start(); p2.start()
p1.join(); p2.join()
# Get return values from each Queue
x = my_q1.get()
y = my_q2.get()
print "RESULT", x, y
print "TOTAL EXECUTION TIME", (time.time() - _start)
从我的机器上来看,结果是:
mpenning@mpenning-T61:~$ python test.py
Got arg1=100
Got arg1=50
RESULT 0.50578212738 1.01011300087
TOTAL EXECUTION TIME 1.02570295334
mpenning@mpenning-T61:~$