#多进程编程
#耗cpu的操作,用多进程编程,对于io操作来说,使用多线程编程,进程切换代价要高于线程
import time
from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor,as_completed
#1、对于耗费cpu的操作,多进程优于多线程
def fib(n):
if n<=2:
return 1
else:
return fib(n-1) + fib(n-2)
# if __name__ == "__main__":
# start_time = time.time()
# with ThreadPoolExecutor(5) as executor:
# #ProcessPoolExecutor
# all_task = [executor.submit(fib,(x)) for x in range(30,45)]
# for future in as_completed(all_task):
# data = future.result()
# print(data)
# print(time.time()-start_time)
#2.对于io操作来说,多线程优于多进程
def random_sleep(n):
time.sleep(n)
return n
if __name__ == "__main__":
start_time = time.time()
with ThreadPoolExecutor(5) as executor:
#ProcessPoolExecutor
all_task = [executor.submit(random_sleep,(x)) for x in [2]*20]
for future in as_completed(all_task):
data = future.result()
print(data)
print(time.time()-start_time)
python多线程————8、多线程与多进程对比
猜你喜欢
转载自blog.csdn.net/sinat_34461756/article/details/83870749
今日推荐
周排行