且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Linux 上的 C 中获取 CPU 信息,例如内核数?

更新时间:2022-10-26 09:15:22

From man 5 proc:

/proc/cpuinfo这是一个依赖于 CPU 和系统架构的集合项目,对于每个受支持的架构,都有一个不同的列表.二常见的条目是处理器,它给出 CPU 编号和波戈米普斯;在内核期间计算的系统常数初始化.SMP 机器具有每个 CPU 的信息.

这里是读取信息并将信息打印到控制台的示例代码,从论坛偷来的 - 它真的只是一个专门的 cat 命令.

#define _GNU_SOURCE#include <stdio.h>#include <stdlib.h>int main(int argc, char **argv){文件 *cpuinfo = fopen("/proc/cpuinfo", "rb");字符 *arg = 0;size_t 大小 = 0;而(getdelim(&arg, &size, 0, cpuinfo) != -1){放(arg);}免费(arg);fclose(cpuinfo);返回0;}

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

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

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

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.