微慑信息网

python 线程池ThreadPoolExecutor操作测试

先贴上代码:

#coding:utf-8
from concurrent.futures import ThreadPoolExecutor,as_completed
import requests
import time

def getHtmllen(url):
    res =  requests.get(url).text
    mlen =len(res)
    return  url,mlen
def start():
    urls = []
    for i in range(435194,435194-20,-1):
        url='http://****/archives/%d.html' % i
        urls.append(url)
    start =time.time()
    '''
    with ThreadPoolExecutor() as pool:
        results = pool.map(getHtmllen,urls)
        for result in results:
            print (result)
    end = time.time()
    print ('cost time is :',end -start)
    '''
    with ThreadPoolExecutor() as pool:
        futures = [pool.submit(getHtmllen, url) for url in urls]
        for future in futures:
            print(future.result())
        #for future in as_completed(futures):
            #print (future.result())
    end = time.time()
    print ("cost times is :",end-start)






def main():
    start()
if __name__ == '__main__':
    main()

其中涉及到2种方式进行线程池操作:

1、

    with ThreadPoolExecutor() as pool:
        results = pool.map(getHtmllen,urls)
        for result in results:
            print (result)

 

2、

    with ThreadPoolExecutor() as pool:
        futures = [pool.submit(getHtmllen, url) for url in urls]
        for future in futures:
            print(future.result())
        #for future in as_completed(futures):
            #print (future.result())

第二种中,有2种方式展示结果,分别为:

按照顺序打印:

for future in futures:
            print(future.result())

乱序打印:

 #for future in as_completed(futures):
            #print (future.result())

注:1、使用map函数,简单;2、future模式更强大

本文标题:python 线程池ThreadPoolExecutor操作测试
本文链接:
(转载请附上本文链接)
http://vulsee.com/archives/vulsee_2021/0906_14681.html
转载请附本站链接,未经允许不得转载,,谢谢:微慑信息网-VulSee.com » python 线程池ThreadPoolExecutor操作测试
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

微慑信息网 专注工匠精神

访问我们联系我们