咨询:Numpy矩阵求逆启用多线程,Scipy单线程运行较慢的原因
Great question! Let’s unpack the behavior you’re seeing step by step:
1. NumPy’s Multithreading Comes From Its Underlying Linear Algebra Libraries
NumPy doesn’t implement matrix inversion from scratch—it relies on optimized linear algebra backends like OpenBLAS, Intel MKL, or BLIS. These libraries are built to use multi-threading for heavy computational tasks (matrix inversion uses LU decomposition under the hood) to leverage multiple CPU cores.
When you call np.linalg.inv(mat), NumPy passes the work to one of these backends, which automatically spins up extra threads to parallelize the computation. That’s why you see 4 total threads (including the main thread) and higher CPU usage—your system is using multiple cores to speed up the task, which triggers the fan as CPU load rises.
2. SciPy’s linalg.inv Uses a Single-Threaded (or Less Parallel) Implementation
SciPy’s linear algebra module (scipy.linalg) often links to different (or differently configured) backend libraries than NumPy. By default, many SciPy builds use a single-threaded version of LAPACK, or don’t enable multi-threading for operations like inversion.
There’s also a thin wrapper layer on top of scipy.linalg.inv, but the main reason for single-threaded behavior is the backend configuration, not the wrapper itself.
3. The Speed Tradeoff: Parallelism vs. Single-Threaded Overhead
- NumPy’s faster runtime: Even with minor thread management overhead, parallelizing the matrix inversion across multiple cores more than makes up for it—hence why it’s ~20% faster than SciPy’s single-threaded approach.
- SciPy’s lower CPU usage: Since it only uses one thread, CPU utilization stays low, but the computation runs sequentially, making it slower.
Quick Ways to Verify This
- Check NumPy’s backend: Run
np.__config__.show()in your Python shell—this will tell you if NumPy uses OpenBLAS, MKL, etc., and whether multi-threading is enabled. - Force NumPy to use one thread: Set the environment variable
OMP_NUM_THREADS=1(for OpenBLAS/MKL) before running your script. You’ll see NumPy’s runtime drop to match SciPy’s, confirming multi-threading was the speed difference driver.
内容的提问来源于stack exchange,提问作者Xero

