Limit number of threads in numpy Limit number of threads in numpy numpy numpy

Limit number of threads in numpy


Try setting all of the following:

export MKL_NUM_THREADS=1export NUMEXPR_NUM_THREADS=1export OMP_NUM_THREADS=1

Sometimes it's a bit tricky to see where exactly multithreading is introduced.


There are more than the 3 mentioned environmental variables. The followings are the complete list of environmental variables and the package that uses that variable to control the number of threads it spawns. Note than you need to set these variables before doing import numpy:

OMP_NUM_THREADS: openmp,OPENBLAS_NUM_THREADS: openblas,MKL_NUM_THREADS: mkl,VECLIB_MAXIMUM_THREADS: accelerate,NUMEXPR_NUM_THREADS: numexpr

So in practice you can do:

import osos.environ["OMP_NUM_THREADS"] = "4" # export OMP_NUM_THREADS=4os.environ["OPENBLAS_NUM_THREADS"] = "4" # export OPENBLAS_NUM_THREADS=4 os.environ["MKL_NUM_THREADS"] = "6" # export MKL_NUM_THREADS=6os.environ["VECLIB_MAXIMUM_THREADS"] = "4" # export VECLIB_MAXIMUM_THREADS=4os.environ["NUMEXPR_NUM_THREADS"] = "6" # export NUMEXPR_NUM_THREADS=6

Note that as of November 2018 the Numpy developers are working on making this possible to do after you do import numpy as well. I'll update this post once they commit those changes.


In regards to doing this from within a python script as opposed to at the bash prompt, per this thread you can do the following (same commands as the answer above):

import osos.environ["MKL_NUM_THREADS"] = "1" os.environ["NUMEXPR_NUM_THREADS"] = "1" os.environ["OMP_NUM_THREADS"] = "1" 

but you have to put that before you do import numpy. Apparently numpy only checks for this at import.

(this is reposted as an answer based on @kηives comment above.)