You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何阻止Numpy多线程运行?多种常规方案尝试无效

解决Numpy/Scipy多线程无法限制的问题(Numpy 1.22.1 集群环境)

在PC集群环境使用Numpy 1.22.1时,需限制Numpy及Scipy的多线程运行,尝试以下常规方案均未解决问题:

  • 设置OMP_NUM_THREADS、OPENBLAS_NUM_THREADS等环境变量为1,确认变量生效后进程仍占用约70个线程
  • 调用mkl.set_num_threads(1),问题依旧存在
  • 确认Numpy依赖OpenBLAS而非MKL后,尝试通过ctypes加载OpenBLAS库设置线程数,仍无效果

最终通过threadpoolctl库的threadpool_limits函数限制BLAS线程数为1,成功解决问题。

实现代码示例

上下文管理器方式(临时限制)

from threadpoolctl import threadpool_limits

# 在上下文内限制BLAS线程数为1
with threadpool_limits(limits=1, user_api='blas'):
    # 执行你的Numpy/Scipy计算逻辑
    import numpy as np
    mat = np.random.rand(2000, 2000)
    mat_product = np.dot(mat, mat)

全局设置方式

from threadpoolctl import threadpool_limits

# 全局限制BLAS线程数为1,后续所有相关运算均受此约束
threadpool_limits(limits=1, user_api='blas')

# 后续执行Numpy/Scipy代码
import numpy as np
import scipy.linalg as la
mat = np.random.rand(2000, 2000)
inv_mat = la.inv(mat)

内容的提问来源于stack exchange,提问作者Jan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 09:27:06