Python 線程池-學習筆記

#! /usr/bin/env python# -*- coding: utf-8 -*-如下代碼可添加進爬蟲任務中,避免屢次建立線程對象,避免電腦卡死避免使用 threading 的Threadfrom concurrent.futures import ThreadPoolExecutorimport timedef sayhello(a):    print("hello: " + a)    time.sleep(2)def main():    seed = ["a", "b", "c"]    start1 = time.time()    for each in seed:        sayhello(each)    end1 = time.time()    print("time1: " + str(end1 - start1))    start2 = time.time()    with ThreadPoolExecutor(3) as executor:        for each in seed:            executor.submit(sayhello, each)    end2 = time.time()    print("time2: " + str(end2 - start2))    start3 = time.time()    with ThreadPoolExecutor(3) as executor1:        executor1.map(sayhello, seed)    end3 = time.time()    print("time3: " + str(end3 - start3))if __name__ == '__main__':    main()
相關文章
相關標籤/搜索