我有两个简单的函数(一个范围上的循环),可以不依赖地单独运行。我试图使用Python多处理模块和多线程模块运行这两个函数。
当我比较输出时,我看到多进程应用程序比多线程模块多花了1秒。
我读到多线程并不那么有效,因为全球解释器锁.
根据上述声明-
多线程模块。
from multiprocessing import Process
import thread
import platform
import os
import time
import threading
class Thread1(threading.Thread):
def __init__(self,threadindicator):
threading.Thread.__init__(self)
self.threadind = threadindicator
def run(self):
starttime = time.time()
if self.threadind == 'A':
process1()
else:
process2()
endtime = time.time()
print 'Thread 1 complete : Time Taken = ', endtime - starttime
def process1():
starttime = time.time()
for i in range(100000):
for j in range(10000):
pass
endtime = time.time()
def process2():
for i in range(1000):
for j in range(1000):
pass
def main():
print 'Main Thread'
starttime = time.time()
thread1 = Thread1('A')
thread2 = Thread1('B')
thread1.start()
thread2.start()
threads = []
threads.append(thread1)
threads.append(thread2)
for t in threads:
t.join()
endtime = time.time()
print 'Main Thread Complete , Total Time Taken = ', endtime - starttime
if __name__ == '__main__':
main()多进程模块
from multiprocessing import Process
import platform
import os
import time
def process1():
# print 'process_1 processor =',platform.processor()
starttime = time.time()
for i in range(100000):
for j in range(10000):
pass
endtime = time.time()
print 'Process 1 complete : Time Taken = ', endtime - starttime
def process2():
# print 'process_2 processor =',platform.processor()
starttime = time.time()
for i in range(1000):
for j in range(1000):
pass
endtime = time.time()
print 'Process 2 complete : Time Taken = ', endtime - starttime
def main():
print 'Main Process start'
starttime = time.time()
processlist = []
p1 = Process(target=process1)
p1.start()
processlist.append(p1)
p2 = Process(target = process2)
p2.start()
processlist.append(p2)
for i in processlist:
i.join()
endtime = time.time()
print 'Main Process Complete - Total time taken = ', endtime - starttime
if __name__ == '__main__':
main()发布于 2013-10-11 21:22:05
如果您有两个CPU可用在您的机器上,您有两个进程不需要通信,您想要使用这两个进程使您的程序更快,您应该使用多处理模块,而不是线程模块。
全局解释器锁(GIL)阻止Python解释器通过使用多个线程有效地使用多个CPU,因为一次只能执行一个Python字节码。因此,多线程不会改善应用程序的总体运行时,除非有阻塞(例如等待IO)或释放GIL的调用(例如,numpy会对一些昂贵的调用进行长时间的调用)。但是,多处理库会创建单独的子进程,因此会创建多个解释器的副本,因此可以高效地使用多个CPU。
但是,在您给出的示例中,您有一个进程完成得非常快(在我的机器上不到0.1秒),一个进程在另一个进程上大约需要18秒才能完成。具体数字可能会根据您的硬件而有所不同。在这种情况下,几乎所有的工作都发生在一个进程中,因此您实际上只使用一个CPU。在这种情况下,生成进程与线程之间的开销增加可能会导致基于进程的版本更慢。
如果让这两个进程执行18秒的嵌套循环,您应该会看到多处理代码运行得更快(假设您的机器实际上有多个CPU)。在我的机器上,我看到多处理代码在18.5秒内完成,多线程代码在71.5秒内完成。我不知道为什么多线程线程花费的时间超过36秒,但我猜想GIL会导致某种类型的线程争用问题,从而减缓了两个线程的执行速度。
至于第二个问题,假设系统上没有其他负载,您应该使用与系统上CPU数量相等的多个进程。您可以通过在Linux系统上执行lscpu、在Mac系统上运行sysctl hw.ncpu或在Windows上运行dxdiag对话框(可能还有其他方法,但我总是这样做)来发现这一点。
对于第三个问题,计算额外进程的效率的最简单方法是使用time.time()或time实用程序(例如time python myprog.py)来度量程序的总运行时。理想的加速比应该等于您正在使用的进程数,因此在4个CPU上运行的4个进程程序最多应该比一个进程的相同程序快4倍,假设您从额外的进程中获得了最大的好处。如果其他进程对您没有多大帮助,它将不到4倍。
https://stackoverflow.com/questions/19326582
复制相似问题