result存储的是线程的返回结果,因此可以用线程池获取返回。
最终时间比
single 3.388930559158325 multi 2.5222535133361816
import threading
import time
ind=3
def single():
for j in range(ind):
for i in range(5000):
w=2*i
print(w)
return '123'
def s(w):
for i in range(5000):
w=2*i
print(w)
return '123'
def multi():
threa=[]
for j in range(ind):
t=threading.Thread(target=s)
threa.append(t)
for t in threa:
t.start()
for t in threa:
t.join()
import concurrent.futures
if __name__ == '__main__':
dan_sum=0
multi_sum=0
start=time.time()
single()
end=time.time()
sum=0
sum1=0
sum=end-start
start=time.time()
with concurrent.futures.ThreadPoolExecutor() as pool:
results=pool.map(s,[i for i in range(ind)])
end=time.time()
sum1=end-start
for i in results:
print(i)
print('single',sum,'multi',sum1,dan_sum,multi_sum)