Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I retrieve the number of processors on C / Linux?

I am writing a small C application that use some threads for processing data. I want to be able to know the number of processors on a certain machine, without using system() & in combination to a small script.

The only way i can think of is to parse /proc/cpuinfo. Any other useful suggestions ?

like image 374
Andrei Ciobanu Avatar asked Apr 22 '10 19:04

Andrei Ciobanu


People also ask

How do I find the number of my processors?

Press Ctrl + Shift + Esc to open Task Manager. Select the Performance tab to see how many cores and logical processors your PC has.

How many cores does my virtual machine have Linux?

The way to tell how may cores you have is to look for "cpu cores" in your /proc/cpuinfo file. This line will show up for each virtual processor. If the number of cores shown is less than the number of virtual processors, your system is multi-threading.

How do I tell how many processors I have Ubuntu?

Method 1: Finding the number of cores in Ubuntu using the “lscpu” command. The 'lscpu' command provides all the information related to the CPU Architecture. The above command will show all the information related to the CPU, like CPU Architecture, the number of CPU cores, threads per core, etc.


2 Answers

As others have mentioned in comments, this answer is useful:

numCPU = sysconf( _SC_NPROCESSORS_ONLN );

Leaving as a solution for folks that might skip over comments...

like image 103
mgalgs Avatar answered Sep 18 '22 10:09

mgalgs


Why not use sys/sysinfo.h?

#include <sys/sysinfo.h>
#include <stdio.h>
void main () {
   printf ("You have %d processors.\n", get_nprocs ());
}

Way more information can be found on the man page

$ man 3 get_nprocs
like image 36
user2445797 Avatar answered Sep 18 '22 10:09

user2445797