如何在 Linux 上的 C 中获取 CPU 信息,例如内核数? [英] How to get CPU info in C on Linux, such as number of cores?

查看:28
本文介绍了如何在 Linux 上的 C 中获取 CPU 信息,例如内核数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

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.

这篇关于如何在 Linux 上的 C 中获取 CPU 信息,例如内核数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆