假设某种场景,比如你要获取多个账号的多种数据,多个阿里云账号获取每个账号6个月账单
耗时写法
from concurrent.futures import ThreadPoolExecutor
dic=[]
pool=ThreadPoolExecutor(max_workers=6)#max_workers是指要开启的线程数
for i in range(0,6):
shit0 = pool.submit(ali_pay2, 0, config).result()
dic.append(shit0.result())
result是阻塞的,如果这样写是等当前线程执行完毕后,获取结果,并没有起到线程并行的效果,一个线程分析完数据大概要2-3秒,耗时差不多12-15秒,一个get请求时间太长
省时间的写法
shit0 = pool.submit(ali_pay2, 0 ,config)
shit1 = pool.submit(ali_pay2, 1, config)
shit2 = pool.submit(ali_pay2, 2, config)
shit3 = pool.submit(ali_pay2, 3, config)
shit4 = pool.submit(ali_pay2, 4, config)
shit5 = pool.submit(ali_pay2, 5, config)
dic.append(shit0.result())
··································
dic.append(shit5.result())
这样写的话就是同时6个线程并行,只需要3-5秒