Python multi-process VS multi-thread (多核CPU利用率)

本文通过实际案例对比了Python中多进程与多线程的CPU利用率,并得出结论:由于GIL的存在,多线程在多核环境下无法充分利用CPU资源,而多进程则可以有效提升性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

现在用python开发服务器代码,因此简单对比了一下其multi-process和multi-thread的CPU利用率

对比图(top命令),结论:python(cpython)由于GIL的存在无法使用threading充分利用CPU资源,如果服务器为多核,请考虑使用multi-process提升性能

多进程( multi-process)

多线程(multi-thread)


源代码

多进程( multi-process)

import multiprocessing

def thread_func(): 
    print "thread in"
    while True:
        pass

if __name__ == "__main__":
    t1 = multiprocessing.Process(target = thread_func)
    t1.start()

    t2 = multiprocessing.Process(target = thread_func)
    t2.start()
    
    t1.join()
    t2.join()

多线程(multi-thread)

from threading import  Thread                                                                                       

def thread_func(): 
    print "thread in"
    while True:
        pass

if __name__ == "__main__":
    t1 = Thread(target = thread_func)
    t1.start()

    t2 = Thread(target = thread_func)
    t2.start()
    
    t1.join()
    t2.join()


转载于:https://www.cnblogs.com/hanhuilee/archive/2013/05/14/5221342.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值