python并行编程:使用 joblib / threadpoolctl 实现后端线程数可控的并行化科学计算编程 —— 实现不同线程池下的numpy矩阵计算
相关地址:
https://github.com/joblib/threadpoolctl

测试代码:
from threadpoolctl import threadpool_limits
import numpy as np
import time
with threadpool_limits(limits=1, user_api='blas'):
# In this block, calls to blas implementation (like openblas or MKL)
# will be limited to use only one thread. They can thus be used jointly
# with thread-parallelism.
a = np.random.randn(10000, 10000)
a_time = time.time()
for _ in range(100):
a_squared = a @ a
b_time = time.time()
print(b_time - a_time)
以上代码运行时的CPU使用率:

设置8线程的线程池进行numpy的并行计算:
代码如下:
from threadpoolctl import threadpool_limits
import numpy as np
import time
with threadpool_limits(limits=8, user_api='blas'):
# In this block, calls to blas implementation (like openblas or MKL)
# will be limited to use only one thread. They can thus be used jointly
# with thread-parallelism.
a = np.random.randn(10000, 10000)
a_time = time.time()
for _ in range(100):
a_squared = a @ a
b_time = time.time()
print(b_time - a_time)
运行时的CPU使用率:

理论上来说该种设置后CPU的使用率应该是800%,但是因为电脑上有其他的计算任务运行,于是有了上面的表现;虽然该测试环境不是很理想,但是至少可以看到numpy进行矩阵计算时的多线程性能还是可以对计算性能有着较大性能提升的。
numpy进行矩阵计算时后端进行多线程的并行计算:
具体情况如下:
默认numpy后端设置:
代码如下:
from threadpoolctl import threadpool_limits
import numpy as np
import time
a = np.random.randn(10000, 10000)
a_time = time.time()
for _ in range(100):
a_squared = a @ a
b_time = time.time()
print(b_time - a_time)



可以看到,numpy进行矩阵计算时默认后端使用主机的所有逻辑核心(该电脑为9700K CPU,8个逻辑核心),每个核心上运行一个线程。
本博客是博主个人学习时的一些记录,不保证是为原创,个别文章加入了转载的源地址,还有个别文章是汇总网上多份资料所成,在这之中也必有疏漏未加标注处,如有侵权请与博主联系。
如果未特殊标注则为原创,遵循 CC 4.0 BY-SA 版权协议。
posted on 2026-02-07 22:46 Angry_Panda 阅读(36) 评论(0) 收藏 举报
浙公网安备 33010602011771号