線程池

#! /usr/bin/env python
# -*- coding: utf-8 -*-
# see https://www.cnblogs.com/zhang293/p/7954353.html

import time
from concurrent.futures import ThreadPoolExecutor


def say_hello(a):
    print("hello: "+a)
    time.sleep(2)


def main():
    '''測試單線程於多線程之間運行效率'''
    seed = ["a", "b", "c"]

    # 單線程運行3次 say_hello 函數
    start1 = time.time()
    for each in seed:
        say_hello(each)
    end1 = time.time()
    print("time1: " + str(end1 - start1))

    # 開啓三個線程,使用 submit 提交任務
    start2 = time.time()
    with ThreadPoolExecutor(3) as executor:
        for each in seed:
            executor.submit(say_hello, each)
    end2 = time.time()
    print("time2: " + str(end2 - start2))

    # 開啓三個線程,使用 map 提交任務
    start3 = time.time()
    with ThreadPoolExecutor(3) as executor1:
        executor1.map(say_hello, seed)
    end3 = time.time()
    print("time3: " + str(end3 - start3))


if __name__ == '__main__':
    main()

運行結構:

hello: a
hello: b
hello: c
time1: 6.006227016448975
hello: a
hello: b
hello: c
time2: 2.005681276321411
hello: a
hello: b
hello: c
time3: 2.005354881286621

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章