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

如何通过Pip安装性能媲美conda版的NumPy?

让pip安装的NumPy拥有与conda版本相同性能的方法

conda安装的NumPy性能更优,核心原因是它默认绑定了Intel MKL或OpenBLAS这类优化过的线性代数库,而pip默认安装的预编译版本往往未启用这些优化,或者仅用了基础编译选项。要让pip版本追平性能,可按以下步骤操作:

  • 安装编译依赖
    首先确保系统具备编译NumPy所需的工具和依赖库:

    • Linux:安装gcc、gfortran、openblas-devel(或intel-mkl-devel)
    • Windows:安装Visual Studio Build Tools(勾选"C++开发工具")
    • macOS:安装Xcode Command Line Tools(运行xcode-select --install)
  • 指定优化库编译安装
    通过设置环境变量,让pip编译NumPy时链接MKL或OpenBLAS:

    • 用MKL优化(需先安装MKL库):
      # Linux/macOS
      export CFLAGS="-march=native -O3"
      export LDFLAGS="-lmkl_rt"
      pip install numpy --no-binary :all:
      
      Windows可在PowerShell中设置环境变量后执行安装:
      $env:CFLAGS = "-march=native -O3"
      $env:LDFLAGS = "-lmkl_rt"
      pip install numpy --no-binary :all:
      
    • 用OpenBLAS优化:
      # Linux/macOS
      export CFLAGS="-march=native -O3"
      export LDFLAGS="-lopenblas"
      pip install numpy --no-binary :all:
      
  • 通过配置文件指定库路径
    如果优化库安装在非默认路径,可创建site.cfg文件指定路径后编译:
    示例site.cfg(针对MKL):

    [mkl]
    library_dirs = /usr/local/lib/mkl
    include_dirs = /usr/local/include/mkl
    mkl_libs = mkl_rt
    lapack_libs =
    

    然后执行:

    pip install numpy --no-binary :all:
    
  • 验证优化是否生效
    安装完成后,运行以下代码检查NumPy是否绑定了目标优化库:

    import numpy as np
    np.show_config()
    

    输出中若出现mkl或openblas相关条目,说明优化已启用。也可通过简单的矩阵乘法测试对比性能:

    import numpy as np
    import time
    
    a = np.random.rand(1000, 1000)
    b = np.random.rand(1000, 1000)
    
    start = time.time()
    c = np.dot(a, b)
    print(f"矩阵乘法耗时: {time.time() - start:.2f} 秒")
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 02:15:44