How to get CPU info in C on Linux, such as number of cores?

52,828

Solution 1

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.

Solution 2

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

Solution 3

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;
}

Solution 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

Solution 5

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.

Share:
52,828
Mickey Shine
Author by

Mickey Shine

Updated on July 05, 2022

Comments

  • Mickey Shine
    Mickey Shine almost 2 years

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

  • Kimvais
    Kimvais about 12 years
    The library did not compile out-of-the-box on my linux box.
  • talonmies
    talonmies about 12 years
    @Kimvais: All I can say is that it works for me.
  • Kimvais
    Kimvais about 12 years
    yep, didn't really troubleshoot, just did configure && make && sudo make install and make failed, might be something really simple :)
  • Laz
    Laz about 12 years
    Curious question. Who updates this file?
  • Kimvais
    Kimvais about 12 years
    @RamBhat - it is not file in general sense. See the Wikipedia article about procfs
  • warunapww
    warunapww over 11 years
    I found this article very helpful, in terms of understanding the /proc/cpuinfo file - richweb.com/cpu_info
  • warunapww
    warunapww over 11 years
    No its not, this will count the hyperthreads as well, please read - richweb.com/cpu_info for detailed info decoding /proc/cpuinfo file.
  • Mark
    Mark over 9 years
    this is the most 'programmatical', possibly simplest way; although man sysconf() specifies that the value "may not be standard"
  • rasjani
    rasjani almost 8 years
    For people who came here looking for help with QNX - there's no such method in base qnx660 as sysinfo_numcpu()
  • Yokai
    Yokai over 6 years
    Useless usage of cat. The following will work just fine: grep -m1 "cores" /proc/cpuinfo | tr -d '[a-z]:[:space:]'
  • Zibri
    Zibri about 5 years
    Threads: cat /proc/cpuinfo | grep -c "cpu cores" ## Cores: cat /proc/cpuinfo | grep -m 1 "cpu cores"|cut -d ":" -f 2
  • hunter_tech
    hunter_tech about 2 years
    any libraries suitable to read the file ?