【发布时间】:2020-03-17 09:34:10
【问题描述】:
所有文档都指出,使用 threading 库运行 python 程序并不能真正让您在 Cpython 解释器的多个内核上运行该程序。但是,CPU 使用率表明它正在使用多个内核。这怎么可能?
我确实使用
验证了 python 解释器是 Cpythonimport platform
platform.python_implementation() # output-> 'Cpython'
Python 版本 - 3.5.2
操作系统 - ubuntu
线程代码
import threading
import math
def fizz():
print ("start")
for i in range (1, 100000000):
math.sqrt(i)
print(" exit")
threads = []
n = 4
for _ in range (n):
t = threading.Thread(target=fizz)
threads.append(t)
for t in threads:
t.start()
for t in threads:
t.join()
print ("Done")
运行程序前的CPU使用率(运行top)
op - 09:27:44 up 235 days, 11:41, 8 users, load average: 0.27, 0.23, 0.13
Tasks: 530 total, 1 running, 522 sleeping, 7 stopped, 0 zombie
%Cpu0 : 0.0 us, 0.0 sy, 0.0 ni,100.0 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
%Cpu1 : 0.0 us, 0.3 sy, 0.0 ni, 99.7 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
%Cpu2 : 0.3 us, 0.3 sy, 0.0 ni, 99.3 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
%Cpu3 : 0.3 us, 0.0 sy, 0.0 ni, 99.7 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
运行程序时的CPU使用率
op - 09:29:29 up 235 days, 11:43, 8 users, load average: 0.39, 0.24, 0.14
Tasks: 530 total, 1 running, 522 sleeping, 7 stopped, 0 zombie
%Cpu0 : 26.0 us, 0.7 sy, 0.0 ni, 73.0 id, 0.0 wa, 0.0 hi, 0.0 si, 0.3 st
%Cpu1 : 24.5 us, 1.0 sy, 0.0 ni, 74.2 id, 0.0 wa, 0.0 hi, 0.0 si, 0.3 st
%Cpu2 : 25.0 us, 0.3 sy, 0.0 ni, 74.7 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
%Cpu3 : 26.1 us, 0.0 sy, 0.0 ni, 73.9 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
【问题讨论】:
-
你确定使用多核的程序和你写的一样吗?请检查哪个进程也在使用 CPU
-
是的,尝试 3 个线程,然后 2 个线程只是为了检查它是您的程序使用内核。
标签: python python-3.x python-multiprocessing python-multithreading gil