12

Is it possible to get such info by some API or function, rather than parsing the /proc/cpuinfo?

1

9 Answers 9

12

From man 5 proc:

   /proc/cpuinfo
          This is a collection of CPU and  system  architecture  dependent
          items,  for  each  supported architecture a different list.  Two
          common  entries  are  processor  which  gives  CPU  number   and
          bogomips;  a  system  constant  that is calculated during kernel
          initialization.  SMP machines have information for each CPU.

Here is sample code that reads and prints the info to console, stolen from forums - It really is just a specialized cat command.

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
   FILE *cpuinfo = fopen("/proc/cpuinfo", "rb");
   char *arg = 0;
   size_t size = 0;
   while(getdelim(&arg, &size, 0, cpuinfo) != -1)
   {
      puts(arg);
   }
   free(arg);
   fclose(cpuinfo);
   return 0;
}

Please note that you need to parse and compare the physical id, core id and cpu cores to get an accurate result, if you really care about the number of CPUs vs. CPU cores. Also please note that if there is a htt in flags, you are running a hyper-threading CPU, which means that your mileage may vary.

Please also note that if you run your kernel in a virtual machine, you only see the CPU cores dedicated to the VM guest.

Sign up to request clarification or add additional context in comments.

3 Comments

Curious question. Who updates this file?
@RamBhat - it is not file in general sense. See the Wikipedia article about procfs
I found this article very helpful, in terms of understanding the /proc/cpuinfo file - richweb.com/cpu_info
10

You can use this for mostly all kind of linux distro

For C code

 num_cpus = sysconf( _SC_NPROCESSORS_ONLN );

(In QNX systems , you can use num_cpus = sysinfo_numcpu())

For shell scripting, you can use cat /proc/cpuinfo

or use lscpu or nproc commands in linux

2 Comments

this is the most 'programmatical', possibly simplest way; although man sysconf() specifies that the value "may not be standard"
For people who came here looking for help with QNX - there's no such method in base qnx660 as sysinfo_numcpu()
5

libcpuid provides a simple API which will directly return all the CPU features, including number of cores. To get the number of cores at runtime, you could do something like this:

#include <stdio.h>
#include <libcpuid.h>

int main(void)
{
    if (!cpuid_present()) {
        printf("Sorry, your CPU doesn't support CPUID!\n");
        return -1;
    }

    struct cpu_raw_data_t raw; 
    struct cpu_id_t data;     

    if (cpuid_get_raw_data(&raw) < 0) { 
        printf("Sorry, cannot get the CPUID raw data.\n");
        printf("Error: %s\n", cpuid_error());
        return -2;
    }

    if (cpu_identify(&raw, &data) < 0) {    
        printf("Sorrry, CPU identification failed.\n");
        printf("Error: %s\n", cpuid_error());
        return -3;
    }

    printf("Processor has %d physical cores\n", data.num_cores);
    return 0;
}

3 Comments

The library did not compile out-of-the-box on my linux box.
@Kimvais: All I can say is that it works for me.
yep, didn't really troubleshoot, just did configure && make && sudo make install and make failed, might be something really simple :)
4

Read /proc/cpuinfo

Sample Output

processor   : 0
model name  : Intel(R) Xeon(R) CPU           E5410  @ 2.33GHz
cache size  : 6144 KB
physical id : 0
siblings    : 4
core id     : 0
cpu cores   : 4
processor   : 1
model name  : Intel(R) Xeon(R) CPU           E5410  @ 2.33GHz
cache size  : 6144 KB
physical id : 0
siblings    : 4
core id     : 1
cpu cores   : 4
processor   : 2
model name  : Intel(R) Xeon(R) CPU           E5410  @ 2.33GHz
cache size  : 6144 KB
physical id : 0
siblings    : 4
core id     : 2
cpu cores   : 4
processor   : 3
model name  : Intel(R) Xeon(R) CPU           E5410  @ 2.33GHz
cache size  : 6144 KB
physical id : 0
siblings    : 4
core id     : 3
cpu cores   : 4

show_cpuinfo is the function which actually implements the /proc/cpuinfo functionality

Comments

2

Add following line in your source code..

system("cat /proc/cpuinfo | grep processor | wc -l");

This will print number of cpus in your system. And if you want to use this output of this system call in your program than use popen system call.

2 Comments

No its not, this will count the hyperthreads as well, please read - richweb.com/cpu_info for detailed info decoding /proc/cpuinfo file.
Threads: cat /proc/cpuinfo | grep -c "cpu cores" ## Cores: cat /proc/cpuinfo | grep -m 1 "cpu cores"|cut -d ":" -f 2
1

Parse the file /proc/cpuinfo. This'll give you lot of details about the CPU. Extract the relevant fields into your C/C++ file.

1 Comment

any libraries suitable to read the file ?
1

No, it is not. Either you must parse cpuinfo file, or some library will do it for you.

Comments

1

Depending on your flavor of Linux you will get different results from /proc/cpuid.

This works for me on CentOS for getting total number of cores.

cat /proc/cpuinfo | grep -w cores | sed -e 's/\t//g' | awk '{print $3}' | xargs | sed -e 's/\ /+/g' | bc

The same doesn't work in Ubuntu. For Ubuntu you can use the following command.

nproc

3 Comments

Useless usage of cat. The following will work just fine: grep -m1 "cores" /proc/cpuinfo | tr -d '[a-z]:[:space:]'
This is for use on a shell. OP asked how to do this programmatically in the C language, not in a shell.
The command cat /proc/cpuinfo | grep -w cores | sed -e 's/\t//g' | awk '{print $3}' | xargs | sed -e 's/\ /+/g' | bc worked at least on Ubuntu-22.04.
0

Have you ever seen the output of this shell command "cat /proc/cpuinfo"? I think there you can get out all the information that you need. To read the information in a C program I would prefer the file manipulation functions like fopen, fgets and so on.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.