使用并行线程提高Python执行速度

假设我有以下示例代码:

x = foo1(something1)
y = foo2(something2)

z = max(x, y)

我想通过使用线程来缩短此代码的执行时间(希望对您有所帮助吗?).我想使事情尽可能简单,所以基本上我想做的是创建同时工作的两个线程,分别计算foo1和foo2.

我正在阅读有关线程的内容,但是我发现它有些棘手,并且我不会因为做这么简单的事情而在其中浪费太多时间.

解决方法:

假设foo1或foo2是CPU绑定的,线程并不能改善执行时间…实际上,通常它会使情况更糟…有关更多信息,请参见David Beazley’s PyCon2010 presentation on the Global Interpreter Lock /Pycon2010 GIL slides.此演示非常有用,我强烈建议您这样做尝试在CPU内核之间分配负载的任何人.

改善性能的最好方法是使用multiprocessing module

假设foo1()和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:~$
上一篇:boost.python c多线程


下一篇:python – 如何检查线程当前是否包含GIL?