#! /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