Snippets

Lilian Besson (Naereen) Count the number of CPU on a Linux machine with a tiny MATLAB/Octave script

Created by Lilian Besson (Naereen) last modified
% Count the number of CPU on a Linux machine with a MATLAB/Octave tiny script
% WARNING: the variable nproc should do the same, please try first to see if it is available on your MATLAB or Octave
%
function nb = countcpu()
    % nb = countcpu()
    %     Return the number of CPU core on your Linux machine (Linux only!).
    %
    %     - How: Read and parse the special file /proc/cpuinfo to count the number of line tagged as 'processor'
    %     - Author: Lilian Besson (https://bitbucket.org/lbesson)
    %     - Web: https://bitbucket.org/snippets/lbesson/G6q7E/
    %     - License: MIT Licensed (http://lbesson.mit-license.org/)
    %     - Date: 02-05-2016

    try
        nb = 0;  % Start with no CPU core
        myfile = fopen('/proc/cpuinfo', 'r');  % Open the special file /proc/cpuinfo
        ansRead = fgets(myfile);  % Start to read it (line by line)
        while ischar(ansRead)  % ansRead is -1 if we read all the file
            % If we read more than 9 characters
            % And if the beginning of the line is 'processor'
            if (length(ansRead) >= 9) && strcmp(ansRead(1:9), 'processor')
                % Then we detected one more CPU core
                nb = nb + 1;
            end;
            ansRead = fgets(myfile);  % Still reading it (line by line)
        end;
        % Done, we close the file and return [nb].
        fclose(myfile);
    catch
        % disp('countcpu(): error when opening /proc/cpuinfo or reading or parsing it. Returning 1 as nb.');
        printf('countcpu(): error (%s) when opening /proc/cpuinfo or reading or parsing it. Returning 1 as nb.\n', lasterr);
        % Thanks to https://stackoverflow.com/questions/12115046/in-gnu-octave-how-to-catch-an-exception#comment16199450_12115169
        nb = 1;
    end;
end;

Comments (0)