是否有可能通过某些API或函数获取此类信息,而不是parsing/proc/cpuinfo
?
从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.
这里是示例代码,读取和打印信息到控制台, 从论坛上被盗 – 这真的只是一个专门的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; }
请注意,如果您真正关心CPU数量与CPU内核数量,则需要解析和比较physical id
, core id
和cpu cores
以获得准确的结果。 另外请注意,如果flags
有htt
,则表示正在运行超线程CPU,这意味着您的里程可能会有所不同。
另请注意,如果您在虚拟机中运行内核,则只能看到专用于VM guest虚拟机的CPU内核。
阅读/proc/cpuinfo
示例输出
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_cpuinfo是实际实现/proc/cpuinfo
功能的函数
你可以使用这个主要是所有类型的Linux发行版
对于C代码
num_cpus = sysconf( _SC_NPROCESSORS_ONLN );
(在QNX系统中,可以使用num_cpus = sysinfo_numcpu()
)
对于shell脚本,可以使用cat /proc/cpuinfo
或者在linux中使用lscpu
或nproc
命令
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; }
解析文件/ proc / cpuinfo。 这会给你很多有关CPU的细节。 将相关字段提取到您的C / C ++文件中。
在源代码中添加以下行
system("cat /proc/cpuinfo | grep processor | wc -l");
这将在您的系统中打印cpus的数量。 如果你想在你的程序中使用这个系统调用的输出,而不是使用popen系统调用。
不它不是。 要么你必须解析cpuinfo文件,或者一些库会为你做。
根据你的Linux的风格,你会从/ proc / cpuid得到不同的结果。
这在CentOS上适用于获取核心总数。
cat /proc/cpuinfo | grep -w cores | sed -e 's/\t//g' | awk '{print $3}' | xargs | sed -e 's/\ /+/g' | bc
在Ubuntu中也是一样。 对于Ubuntu,您可以使用以下命令。
nproc
你见过这个shell命令的输出“cat / proc / cpuinfo”吗? 我想在那里你可以得到你需要的所有信息。 要读取C程序中的信息,我更喜欢文件操作函数,如fopen,fgets等。