Python多进程

from multiprocessing import Pool  #多进程所需要的包
import requests,time
def demo(url):
    # url='https://588ku.com/png-zt/2717/p3.html'
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'}
    html=requests.get(url,headers=headers).text
    return html
if __name__ == '__main__':
    urls = ['https://588ku.com/png-zt/2717/p{}.html'.format(str(i)) for i in range(1, 11)]
    # begin=time.time()
    # for url in urls:
    #     demo(url)
    # end=time.time()
    # print("串行运行时间:",end-begin)      #7.8s
    #
    # begin = time.time()
    # pool=Pool(processes=2)  #自定义进程数量
    # pool.map(demo,urls)
    # end = time.time()
    # print("2进程运行时间:", end - begin)  #4.6s
    #
    # begin = time.time()
    # pool = Pool(processes=4)  
    # pool.map(demo, urls)
    # end = time.time()
    # print("4进程运行时间:", end - begin)  #3.6s

    begin = time.time()
    pool = Pool()   #默认处理器核心数
    text=pool.map(demo, urls)  #获取内容
    print(text)
    end = time.time()
    print("最大进程运行时间:", end - begin) #3.6s,证明此计算机为4核处理器

你可能感兴趣的:(Python多进程)