您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
这篇文章将为大家详细讲解有关Python中多线程与多进程对比的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
多线程适合于多io操作
多进程适合于耗cpu(计算)的操作
# 多进程编程 # 耗cpu的操作,用多进程编程, 对于io操作来说,使用多线程编程 import time from concurrent.futures import ThreadPoolExecutor, as_completed from concurrent.futures import ProcessPoolExecutor def fib(n): if n <= 2: return 1 return fib(n - 2) + fib(n - 1) if __name__ == '__main__': # 1. 对于耗cpu操作,多进程优于多线程 # with ThreadPoolExecutor(3) as executor: # all_task = [executor.submit(fib, num) for num in range(25, 35)] # start_time = time.time() # for future in as_completed(all_task): # data = future.result() # print(data) # print("last time :{}".format(time.time() - start_time)) # 3.905290126800537 # 多进程 ,在window环境 下必须放在main方法中执行,否则抛异常 with ProcessPoolExecutor(3) as executor: all_task = [executor.submit(fib, num) for num in range(25, 35)] start_time = time.time() for future in as_completed(all_task): data = future.result() print(data) print("last time :{}".format(time.time() - start_time)) # 2.6130592823028564
可以看到在耗cpu的应用中,多进程明显优于多线程 2.6130592823028564 < 3.905290126800537
下面模拟一个io操作
# 多进程编程 # 耗cpu的操作,用多进程编程, 对于io操作来说,使用多线程编程 import time from concurrent.futures import ThreadPoolExecutor, as_completed from concurrent.futures import ProcessPoolExecutor def io_operation(n): time.sleep(2) return n if __name__ == '__main__': # 1. 对于耗cpu操作,多进程优于多线程 # with ThreadPoolExecutor(3) as executor: # all_task = [executor.submit(io_operation, num) for num in range(25, 35)] # start_time = time.time() # for future in as_completed(all_task): # data = future.result() # print(data) # print("last time :{}".format(time.time() - start_time)) # 8.00358772277832 # 多进程 ,在window环境 下必须放在main方法中执行,否则抛异常 with ProcessPoolExecutor(3) as executor: all_task = [executor.submit(io_operation, num) for num in range(25, 35)] start_time = time.time() for future in as_completed(all_task): data = future.result() print(data) print("last time :{}".format(time.time() - start_time)) # 8.12435245513916
关于“Python中多线程与多进程对比的示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。