Get CPU count from Matlab

We use this function to capture the number of physical CPU cores available on a computer from Matlab. Like any such function it doesn’t always work, but we try 3 separate methods to help improve accuracy. Knowing the CPU count is useful when running mpiexec from Matlab.

function N = get_cpu_count()
%% get apparent number of physical CPU cores

if isoctave
  N = idivide(nproc, 2);  % assume hyperthreading
else
  N = maxNumCompThreads;
  if N < 2  % happens on some HPC
    N = feature('NumCores');
  end
  if N < 2 && usejava('jvm')
    % assume hyperthreading
    N = java.lang.Runtime.getRuntime().availableProcessors / 2;
  end
end

N = max(N, 1);

end


function isoct = isoctave()
isoct = exist('OCTAVE_VERSION', 'builtin') == 5;
end

Python CPU count