concurrent.futures模块(抽象层)
【1】IO密集型 -- 多线程
【2】计算密集型 -- 多进程
ThreadPoolExecutor
ProcessPoolExecutor
import time
import concurrent.futures
numbers = list (range(1,11))
def count(n)
for i in range(1000000):
i+=1
return i* n
def worker(x):
result count(x)
print(f'数字:{x}的计算结果是{result}')
//顺序执行
def sequntial_execution():
start_time.clock()
for i in numbers:
worker(i)
print(f'顺序执行花费时间:{tim() - start_time}秒')
//多线程执行
def threading_execution():
start_time = time.clock()
with concurrent.futures.ThreadPoolExecutor(max_workers = 5) as excutor:
for i in numbers:
executor.submit(worker,i)
print(f'顺序执行花费时间:{tim() - start_time}秒')
//进程池执行
def process_execution():
start_time = clock.clock()
with concurrent.futures.ProcessPoolExecutor(max_workers = 5) as excutor:
for i in numbers:
executor.submit(worker,i)
print(f'顺序执行花费时间:{tim() - start_time}秒')
if __name__ == '__main__':
sequential_excution()
threading_excution()
process_execution()