多进程在CPU密集型任务中性能优于多线程,因GIL限制多线程并行;而多线程在IO密集型任务中表现良好,适合高并发等待场景。

在Python中,多线程和多进程是实现并发编程的两种常见方式。但由于GIL(全局解释器锁)的存在,多线程在CPU密集型任务中表现不佳,而多进程则能真正利用多核优势。下面通过实际测试对比两者的性能差异。
测试场景设计
为了公平比较,我们设定两个典型任务:
CPU密集型任务:计算大量数字的平方和IO密集型任务:模拟网络请求延迟(使用time.sleep)
分别用单线程、多线程、多进程执行,记录耗时。
CPU密集型任务性能对比
代码示例:
立即学习“Python免费学习笔记(深入)”;
import threadingimport multiprocessingimport timedef cpu_task(n):return sum(i * i for i in range(n))
def single_threadcpu(n, loops):for in range(loops):cpu_task(n)
def multi_threadcpu(n, loops, threads=4):def worker():for in range(loops // threads):cpu_task(n)threadslist = [threading.Thread(target=worker) for in range(threads)]for t in threads_list:t.start()for t in threads_list:t.join()
def multi_process_cpu(n, loops, processes=4):with multiprocessing.Pool(processes) as pool:pool.map(cpu_task, [n] * loops)
测试参数
n = 10000loops = 20
单线程
start = time.time()single_thread_cpu(n, loops)print(f"单线程耗时: {time.time() - start:.2f}s")
多线程
start = time.time()multi_thread_cpu(n, loops)print(f"多线程耗时: {time.time() - start:.2f}s")
多进程
start = time.time()multi_process_cpu(n, loops)print(f"多进程耗时: {time.time() - start:.2f}s")
结果分析:
多线程耗时接近甚至超过单线程,因为GIL限制了并行执行多进程显著快于前两者,充分利用多核CPU
IO密集型任务性能对比
模拟IO操作(如网络请求):
import timeimport threadingimport multiprocessingdef io_task(seconds):time.sleep(seconds)
def single_threadio(loops, sec=0.1):for in range(loops):io_task(sec)
def multi_threadio(loops, sec=0.1, threads=4):def worker():for in range(loops // threads):io_task(sec)threadslist = [threading.Thread(target=worker) for in range(threads)]for t in threads_list:t.start()for t in threads_list:t.join()
def multi_process_io(loops, sec=0.1, processes=4):with multiprocessing.Pool(processes) as pool:pool.map(io_task, [sec] * loops)
测试参数
loops = 40sec = 0.1
单线程
start = time.time()single_thread_io(loops, sec)print(f"IO-单线程耗时: {time.time() - start:.2f}s")
多线程
start = time.time()multi_thread_io(loops, sec)print(f"IO-多线程耗时: {time.time() - start:.2f}s")
多进程
start = time.time()multi_process_io(loops, sec)print(f"IO-多进程耗时: {time.time() - start:.2f}s")
结果分析:
多线程在IO密集型任务中表现优秀,线程休眠时不占用GIL,可切换执行其他任务多进程也能提升效率,但创建开销大,优势不如多线程明显通常IO场景推荐使用多线程或异步(asyncio)
总结与建议
根据测试结果得出以下结论:
涉及大量计算的任务优先选择多进程频繁等待外部资源(如网络、文件读写)的任务适合使用多线程多进程间通信成本高,需考虑数据共享复杂度对于高并发IO场景,可进一步尝试asyncio提升效率
基本上就这些。选择哪种方式,关键看任务类型。理解GIL的影响,才能写出高效的Python并发程序。
以上就是Python多线程性能测试对比 Python多线程与多进程效率分析的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1379402.html
微信扫一扫
支付宝扫一扫