• python 线程池使用


    传统多线程方案会使用“即时创建, 即时销毁”的策略。尽管与创建进程相比,创建线程的时间已经大大的缩短,但是如果提交给线程的任务是执行时间较短,而且执行次数极其频繁,那么服务器将处于不停的创建线程,销毁线程的状态。

    一个线程的运行时间可以分为3部分:线程的启动时间、线程体的运行时间和线程的销毁时间。在多线程处理的情景中,如果线程不能被重用,就意味着每次创建都需要经过启动、销毁和运行3个过程。这必然会增加系统相应的时间,降低了效率。

    使用线程池:
    由于线程预先被创建并放入线程池中,同时处理完当前任务之后并不销毁而是被安排处理下一个任务,因此能够避免多次创建线程,从而节省线程创建和销毁的开销,能带来更好的性能和系统稳定性。

    体验一下使用线程池实现爬虫

    在使用前需要安装线程池类库: 

    pip install threadpool 

    #!/usr/bin/env python 
    # coding:utf-8 
    # @Time : 2018/4/19 16:06
    # @Author : chenjisheng
    # @File : 17zwd_sample.py
    # @Mail : mail_maomao@163.com
    from bs4 import BeautifulSoup
    import threadpool
    import requests
    import threading
    import datetime
    
    baseurl = "http://hz.17zwd.com/sks.htm?cateid=0&page="
    
    
    # 爬虫函数
    def getResponse(url):
        target = baseurl + url
        content = requests.get(target).text
        soup = BeautifulSoup(content, 'lxml')
        tags = soup.find_all('div', attrs={"class": "huohao-img-container"})
        for tag in tags:
            imgurl = tag.find('img').get('data-original')
            # print(imgurl)
    
    
    # 定义线程为 10 个
    starttime = datetime.datetime.now()
    pool = threadpool.ThreadPool(10)
    # 定义线程池的任务
    tasks = threadpool.makeRequests(getResponse, [str(x) for x in range(1, 11)])
    # 使用线程池启动任务
    [pool.putRequest(task) for task in tasks]
    pool.wait()
    endtime = datetime.datetime.now()
    
    alltime = (endtime - starttime).seconds
    print("线程池总耗时为: {}秒".format(alltime))
    # 传统线程
    starttime1 = datetime.datetime.now()
    tasklist = [threading.Thread(target=getResponse(str(x))) for x in range(1, 11)]
    
    for i in tasklist:
        i.start()
    
    for i in tasklist:
        i.join()
    endtime1 = datetime.datetime.now()
    alltime1 = (endtime1 - starttime1).seconds
    
    print("传统线程总耗时为: {}秒".format(alltime1))
    
    if __name__ == "__main__":
        pass

    最后执行结果: 线程池耗时3秒,传统线程耗时9秒;

    差别还是挺大的哈;

  • 相关阅读:
    [转]Intellij IDEA快捷键与使用小技巧
    Swoole来实现实时异步任务队列
    php 异步执行脚本
    Centos 7 systemctl和防火墙firewalld命令
    tgz的解压
    error: C++ preprocessor "/lib/cpp" fails sanity check错误解决方法
    Linux 命令详解(三)./configure、make、make install 命令
    LNMP, CentOS7.0+Nginx+Mysql5.7+PHP7环境安装
    phpmailer使用qq邮箱、163邮箱成功发送邮件实例代码
    Mibew Messenger (also known as Open Web Messenger)
  • 原文地址:https://www.cnblogs.com/Mail-maomao/p/8884794.html
Copyright © 2020-2023  润新知