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

时间:2011-12-08 12:20:02

标签: python multithreading performance multiprocessing gil

假设我有这个示例代码:

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

z = max(x, y)

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

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

4 个答案:

答案 0 :(得分:8)

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

提高效果的最佳方法是使用Pycon2010 GIL slides

假设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:~$ 

答案 1 :(得分:0)

您可以使用python thread模块或新的Threading模块,但使用thread模块的语法更简单,

#!/usr/bin/python

import thread
import time

# Define a function for the thread
def print_time( threadName, delay):
   count = 0
   while count < 5:
      time.sleep(delay)
      count += 1
      print "%s: %s" % ( threadName, time.ctime(time.time()) )

# Create two threads as follows
try:
   thread.start_new_thread( print_time, ("Thread-1", 2, ) )
   thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
   print "Error: unable to start thread"

while 1:
   pass

将输出,

Thread-1: Thu Jan 22 15:42:17 2009
Thread-1: Thu Jan 22 15:42:19 2009
Thread-2: Thu Jan 22 15:42:19 2009
Thread-1: Thu Jan 22 15:42:21 2009
Thread-2: Thu Jan 22 15:42:23 2009
Thread-1: Thu Jan 22 15:42:23 2009
Thread-1: Thu Jan 22 15:42:25 2009
Thread-2: Thu Jan 22 15:42:27 2009
Thread-2: Thu Jan 22 15:42:31 2009
Thread-2: Thu Jan 22 15:42:35 2009

从这里阅读更多内容,Python - Multithreaded Programming

答案 2 :(得分:0)

首先阅读文档here以了解以下代码:

import threading

def foo1(x=0):
    return pow(x, 2)

def foo2(y=0):
    return pow(y, 3)

thread1 = threading.Thread(target=foo1, args=(3))
thread2 = threading.Thread(target=foo2, args=(2))
thread1.start()
thread2.start()
thread1.join()
thread2.join()

答案 3 :(得分:-1)

没有用。阅读Python FAQ。

相关问题