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

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

问题描述

是否有可能被一些API或函数来得到这样的信息,而不是解析的/ proc内/ cpuinfo


解决方案

5人PROC


 的/ proc内/ cpuinfo
          这是CPU和系统体系结构相关的集合
          项目,为每个支持的架构不同的列表。二
          常见条目是处理器,这给CPU数量和
          bogomips;在核心中计算系统不变
          初始化。 SMP机器为每个CPU信息。


下面是示例code读取和打印信息到控制台,<一个href=\"http://www.linuxquestions.org/questions/programming-9/c-get-cmdline-from-proc-filesystem-772529/\"相对=nofollow>从论坛被盗 - 这真的只是一个专门的命令

 的#define _GNU_SOURCE
#包括LT&;&stdio.h中GT;
#包括LT&;&stdlib.h中GT;INT主(INT ARGC,字符** argv的)
{
   FILE * cpuinfo =的fopen(的/ proc内/ cpuinfo,RB);
   字符* ARG = 0;
   为size_t大小= 0;
   而(getdelim(安培;阿根廷,和放大器;!大小,0,cpuinfo)= - 1)
   {
      看跌期权(ARG);
   }
   免费(ARG);
   FCLOSE(cpuinfo);
   返回0;
}

请注意,您需要分析和比较物理ID 核心ID CPU内核来得到一个准确的结果,如果你真的关心的CPU与CPU内核的数量。同时请注意,如果有一个 HTT 标记,您正在运行超线程CPU,这意味着您的里程可能会有所不同。

另外请注意,如果你在一个虚拟机上运行你的内核,你只能看到专门为VM guest虚拟机的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.

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

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