繁体   English   中英

使用 Cpython 运行时,python 程序怎么可能使用多个内核?

[英]How is it possible that the python program is utilizing multiple cores when running using Cpython?

所有文档都指出,使用threading库运行 python 程序并不能真正使您能够在 Cpython 解释器的多核上运行该程序。 但是,CPU 使用率表明它正在使用多个内核。 这怎么可能?

我确实验证了 python 解释器是 Cpython 使用

import 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

我认为文档的意思是使用threading并不能真正同时运行多个线程,这意味着您只能在一个进程中使用一个核心容量,即使您同时运行 4 或 8 个线程。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM