[英]python2.7 threading pool is much faster than starting the thread one by one
我对线程池进行了一些测试并一一启动线程。 使用线程池时速度要快得多。 我能弄清楚为什么?
import threading
import Queue
import time
def stringFunction(value, out_queue):
my_str = "This is string no. " + value
time.sleep(5)
out_queue.put(my_str)
my_queue = Queue.Queue()
i = 1
threads = []
while i<10:
thread = threading.Thread(stringFunction(str(i), my_queue))
thread.start()
threads.append(thread)
i = i + 1
for thread in threads:
thread.join()
func_value = list(my_queue.queue)
print func_value
[运行] python -u "c:\Users\eguozqu\git\test\thread_test.py" ['这是字符串编号。 1', '这是字符串编号。 2', '这是字符串编号。 3', '这是字符串编号。 4', '这是字符串编号。 5', '这是字符串编号。 6', '这是字符串编号。 7', '这是字符串编号。 8', '这是字符串编号。 9']
[完成] 在 45.353 秒内以 code=0 退出
from multiprocessing.pool import ThreadPool as Pool
import time
class someClass(object):
def __init__(self):
pass
def f(self, x):
time.sleep(5)
return x*x
def go(self):
p = Pool(10)
sc = p.map(self, range(10))
print sc
def __call__(self, x):
return self.f(x)
sc = someClass()
sc.go()
[运行中] python -u "c:\Users\eguozqu\git\test\process_test.py" [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[完成] 在 5.393 秒内以 code=0 退出
当您执行threading.Thread(stringFunction(str(i), my_queue))
时,您正在调用stringFunction
并将结果传递给threading.Thread
的初始化程序,而不是传递 function 本身。
这意味着每次创建线程时,您首先等待 function 调用完成。
您可能想要的是threading.Thread(target=stringFunction, args=(str(i), my_queue))
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.