【发布时间】:2020-09-29 14:28:07
【问题描述】:
更新:为了节省您的时间,我直接在这里给出答案。如果您使用纯 Python 编写代码,Python 不能同时使用多个 cpu 内核。但是 Python 可以在调用一些用 C 语言编写的函数或包时同时使用多核,例如 Numpy 等。
我听说“python 中的多线程不是真正的多线程,因为 GIL”。而且我还听说“python多线程可以处理IO密集型任务而不是计算密集型任务,因为只有一个线程同时运行”。
但我的经历让我重新思考了这个问题。我的经验表明,即使对于计算密集型任务,python 多线程 可以 几乎可以加速计算。 (在多线程之前,我运行下面的程序花了我 300 秒,在我使用多线程之后,我花了 100 秒。)
下图显示python以CPython为编译器,包threading创建了5个线程,所有cpu cores的百分比接近100%。
我认为截图可以证明5个cpu核心同时运行。
那么谁能给我解释一下?我可以将多线程应用于 python 中的计算密集型任务吗?或者python中可以多线程/多核同时运行吗?
我的代码:
import threading
import time
import numpy as np
from scipy import interpolate
number_list = list(range(10))
def image_interpolation():
while True:
number = None
with threading.Lock():
if len(number_list):
number = number_list.pop()
if number is not None:
# Make a fake image - you can use yours.
image = np.ones((20000, 20000))
# Make your orig array (skipping the extra dimensions).
orig = np.random.rand(12800, 16000)
# Make its coordinates; x is horizontal.
x = np.linspace(0, image.shape[1], orig.shape[1])
y = np.linspace(0, image.shape[0], orig.shape[0])
# Make the interpolator function.
f = interpolate.interp2d(x, y, orig, kind='linear')
else:
return 1
workers=5
thd_list = []
t1 = time.time()
for i in range(workers):
thd = threading.Thread(target=image_interpolation)
thd.start()
thd_list.append(thd)
for thd in thd_list:
thd.join()
t2 = time.time()
print("total time cost with multithreading: " + str(t2-t1))
number_list = list(range(10))
for i in range(10):
image_interpolation()
t3 = time.time()
print("total time cost without multithreading: " + str(t3-t2))
输出是:
total time cost with multithreading: 112.71922039985657
total time cost without multithreading: 328.45561170578003
【问题讨论】:
-
你用什么代码测试过它?
-
如果它们都有不同的 PID,那么您很可能是不小心使用了多处理。
-
@FiddleStix 是的,我想知道这一点。此外,
509 total, 508 sleeping表明没有实际工作正在完成。 -
@FiddleStix 我在python中使用线程包,所以我认为我没有使用多处理。
-
@Carcigenicate 我认为
509 total, 508 sleeping没有提供有关运行线程号的任何信息。表示任务号或进程号。
标签: python multithreading cpython gil