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

use*_*220 0 python performance multithreading multiprocessing gil

假设我有这个示例代码:

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

z = max(x, y)
Run Code Online (Sandbox Code Playgroud)

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

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

Mik*_*ton 8

假设foo1foo2受CPU限制,线程不会改善执行时间......事实上,它通常会使情况变得更糟......有关更多信息,请参阅David Beazley在Global Interpreter Lock/Pycon2010 GIL幻灯片上的PyCon2010演示.这个演示文稿非常有用,我强烈建议任何试图在CPU内核之间分配负载的人.

提高性能的最佳方法是使用多处理模块

假设在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)
Run Code Online (Sandbox Code Playgroud)

从我的机器,这导致:

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:~$ 
Run Code Online (Sandbox Code Playgroud)