-function [nb] = countcpu()
- % Read and parse the special file /proc/cpuinfo to count the number of CPU on your machine.
- % Author: Lilian Besson (https://bitbucket.org/lbesson)
- % Web: https://bitbucket.org/snippets/lbesson/G6q7E/
- % License: MIT Licensed (http://lbesson.mit-license.org/)
+function 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/)
- myfile = fopen('/proc/cpuinfo', 'r');
- ansRead = fgets(myfile);
- if (length(ansRead) >= 9) && strcmp(ansRead(1:9), 'processor')
- ansRead = fgets(myfile);
+ 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
+ ansRead = fgets(myfile); % Still reading it (line by line)
+ % Done, we close the file and return [nb].
+ % 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