如何在 Linux 上以 C 语言获取 CPU 信息,例如内核数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9629850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 05:03:31  来源:igfitidea点击:

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

clinuxoperating-systemcpu

提问by Mickey Shine

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

是否可以通过某些 API 或函数获取此类信息,而不是解析/proc/cpuinfo?

回答by Kimvais

From man 5 proc:

来自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.
   /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 catcommand.

这是从论坛中窃取的读取信息并将其打印到控制台的示例代码- 它实际上只是一个专门的cat命令。

#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 idand cpu coresto get an accurate result, if you really care about the number of CPUs vs. CPU cores. Also please note that if there is a httin flags, you are running a hyper-threading CPU, which means that your mileage may vary.

请注意,如果您真的关心 CPU 与 CPU 内核的数量,则需要解析和比较physical idcore idcpu cores获得准确的结果。另请注意,如果有httin flags,则您正在运行超线程 CPU,这意味着您的里程可能会有所不同。

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

另请注意,如果您在虚拟机中运行内核,则只能看到专用于 VM 来宾的 CPU 内核。

回答by Pavan Manjunath

Read /proc/cpuinfo

/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_cpuinfois the function which actually implements the /proc/cpuinfofunctionality

show_cpuinfo是实际实现/proc/cpuinfo功能的函数

回答by webgenius

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

解析文件/proc/cpuinfo。这将为您提供有关 CPU 的许多详细信息。将相关字段提取到您的 C/C++ 文件中。

回答by seveves

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.

你见过这个shell命令“cat /proc/cpuinfo”的输出吗?我认为在那里您可以获得所需的所有信息。要读取 C 程序中的信息,我更喜欢 fopen、fgets 等文件操作函数。

回答by talonmies

libcpuidprovides 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:

libcpuid提供了一个简单的 API,它将直接返回所有 CPU 特性,包括内核数。要在运行时获取内核数,您可以执行以下操作:

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

回答by Kunal

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.

这将打印您系统中的 CPU 数量。如果你想在你的程序中使用这个系统调用的这个输出,而不是使用 popen 系统调用。

回答by Marko Kevac

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

不它不是。您必须解析 cpuinfo 文件,或者某些库会为您解析。

回答by Brent D.

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

根据您的 Linux 风格,您将从 /proc/cpuid 获得不同的结果。

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

这适用于我在 CentOS 上获取内核总数。

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

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

这在 Ubuntu 中不起作用。对于 Ubuntu,您可以使用以下命令。

nproc

回答by aditya dogra

You can use this for mostly all kind of linux distro

您可以将它用于几乎所有类型的 linux 发行版

For C code

对于 C 代码

 num_cpus = sysconf( _SC_NPROCESSORS_ONLN );

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

(在 QNX 系统中,您可以使用num_cpus = sysinfo_numcpu()

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

对于 shell 脚本,您可以使用 cat /proc/cpuinfo

or use lscpuor nproccommands in linux

或在 linux 中使用lscpunproc命令