Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 941
Mickey Shine Avatar asked Mar 09 '12 06:03

Mickey Shine


People also ask

Is there some Linux command that can fetch us the CPU info directly?

You can also use the command called lscpu to display information on CPU architecture on modern Linux distributions.

How can you tell how many virtual cores you have in 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 find my CPU information?

Right-click your taskbar and select “Task Manager” or press Ctrl+Shift+Esc to launch it. Click the “Performance” tab and select “CPU.” The name and speed of your computer's CPU appear here. (If you don't see the Performance tab, click “More Details.”)


1 Answers

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.

like image 65
Kimvais Avatar answered Nov 10 '22 00:11

Kimvais