Limit Number of threads in python SimpleITK programatically

I’m using SimpleITK from python. By default all logical CPUs which are found are used, but I like to constrict this. I already read this thread here: Threading in ITK and can confirm that setting the environment variable ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS does work.
However, I would like to be able to set this from the program itself, so I don’t have to mess with the variables all the time.

I found out it is possible to set this inside the python program like:

import os
import psutil
os.environ['ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS'] = str(psutil.cpu_count(logical=False))
import SimpleITK as sitk

But this has to be before importing SimpleITK.
Is it possible to set this also after SimpleITK was imported? I tried importlib.reload(sitk), but this seems to change nothing, the old number of Threads is still used.

Hello @reox,

The SimpleITK process object has a method SetGlobalDefaultNumberOfThreads:

import SimpleITK as sitk
MAX_THREADS = 3

sitk.ProcessObject.SetGlobalDefaultNumberOfThreads(MAX_THREADS)

There’s the matching Get method so that you can find out what is the global default number of threads.

3 Likes

@zivy
great, that works! thank you!

1 Like