python多线程为什么没有跑满CPU?

1、实验环境

Vmvare虚拟机:单处理器2核。

2、Python获取CPU使用率

import psutil

def get_cpu_percent():
    cpu_percent = psutil.cpu_percent(interval=1)
    return cpu_percent

while(1):

    cpu_percent = get_cpu_percent()
    print("当前CPU占用率:{}%".format(cpu_percent))

3、多线程

import threading
def cpu_intensive_task():
    while True:
        pass

# 创建多个线程并启动
for _ in range(10):
    thread = threading.Thread(target=cpu_intensive_task)
    thread.start()

# 等待所有线程执行结束
for thread in threading.enumerate():
    if thread != threading.current_thread():
        thread.join()

多线程——实验结果

如下图所示,CPU占用率为50左右。
在这里插入图片描述

3、多进程

import multiprocessing

def cpu_intensive_task():
    while True:
        # 执行一些需要大量计算的任务
        pass

# 创建多个进程并启动
for _ in range(2):
    process = multiprocessing.Process(target=cpu_intensive_task)
    process.start()

# 等待所有进程执行结束
for process in multiprocessing.active_children():
    process.join()

多进程——实验结果

如下图所示,CPU使用率100%
在这里插入图片描述

结论

由于GIL的关系,python的多线程并没有发挥多核的作用,这些线程都是在在单核上跑的。

python的多线程为什么不能利用多核CPU?
如何让一个Python的脚本跑满多核的CPU

拓展——Java多线程测试

一个线程的情况

public class ThreadDemo01 extends Thread {
    public ThreadDemo01() {
        //编写子类的构造方法,可缺省
    }

    public void run() {
        //编写自己的线程代码
        while(true){
            int a = 0;
        }
            
    }

    public static void main(String[] args) {

        ThreadDemo01 thread01 = new ThreadDemo01();
        //ThreadDemo01 thread02 = new ThreadDemo01();
        thread01.setName("自定义的线程1");
        thread01.start();
        //thread02.setName("自定义的线程2");
        //thread02.start();

        //main线程
        System.out.println(Thread.currentThread().toString());
    }

}

测试结果

单线程的情况下CPU使用率为50%左右
在这里插入图片描述

两个线程的情况

public class ThreadDemo01 extends Thread {
    public ThreadDemo01() {
        //编写子类的构造方法,可缺省
    }

    public void run() {
        //编写自己的线程代码
        while(true){
            int a = 0;
        }
            
    }

    public static void main(String[] args) {
        ThreadDemo01 thread01 = new ThreadDemo01();
        ThreadDemo01 thread02 = new ThreadDemo01();
        thread01.setName("自定义的线程1");
        thread01.start();
        thread02.setName("自定义的线程2");
        thread02.start();
        //main线程
        System.out.println(Thread.currentThread().toString());
    }
}
测试结果

在这里插入图片描述

结论

JAVA的多线程和Python不同,可以充分利用多核性能。
  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值