from concurrent.futures import ThreadPoolExecutor,as_completed
import time
from concurrent.futures import ProcessPoolExecutor
#多进程编程
#耗CPU的操作,用多进程编程,对于IO操作来说,使用多线程编程,进程切换代价高于线程。
#1 对于耗CPU的操作,多进程由于多线程
def fib(n):
if n<=2:
return 1
return fib(n-1)+fib(n-2)
"""
if __name__ == "__main__":#使用多进程一定要加"if __name__ == "__main__"
# 利用多进程测试程序运行的时间 :last time is: 5.340000152587891
with ProcessPoolExecutor(3) as executor:
all_task = [executor.submit(fib, (num)) for num in range(20, 35)]
start_time = time.time()
for future in as_completed(all_task):
data = future.result()
print('exe result {}'.format(data))
print('last time is: {}'.format(time.time() - start_time))
if __name__ == "__main__":
#利用多线程测试程序运行的时间 :last time is: 6.2900002002716064
with ThreadPoolExecutor(max_workers=3) as executor:
all_task=[executor.submit(fib,(num)) for num in range(20, 35)]
start_time=time.time()
for future in as_completed(all_task):
data=future.result()
print('exe result {}'.format(data))
print('last time is: {}'.format(time.time()-start_time))
"""
#2 对于IO操作来说,多线程优于多进程
def random_sleep(n):
time.sleep(n)
return n
"""
if __name__ == "__main__":
# 利用多线程测试程序运行的时间 :20.001999855041504
with ThreadPoolExecutor(max_workers=3) as executor:
all_task = [executor.submit(random_sleep, (num)) for num in [2]*30]#20个2的列表
start_time = time.time()
for future in as_completed(all_task):
data = future.result()
print('exe result {}'.format(data))
print('last time is: {}'.format(time.time() - start_time))
"""
if __name__ == "__main__":
# 利用多进程测试程序运行的时间 :20.47699999809265
with ProcessPoolExecutor(max_workers=3) as executor:
all_task = [executor.submit(random_sleep, (num)) for num in [2]*30]#20个2的列表
start_time = time.time()
for future in as_completed(all_task):
data = future.result()
print('exe result {}'.format(data))
print('last time is: {}'.format(time.time() - start_time))
网友评论