有没有可能通过一些API或函数获取这样的信息,而不是解析/proc/cpuinfo
?
有没有可能通过一些API或函数获取这样的信息,而不是解析/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
命令。请注意,如果您真的关心CPU数量与CPU核心数之间的差异,您需要解析和比较物理ID、核心ID和CPU核心数,以获取准确结果。同时请注意,如果在“flags”中有“htt”,则表示您正在运行支持超线程技术的CPU,这意味着您的性能可能会有所不同。
#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核心。
您可将其用于大多数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;
}
configure && make && sudo make install
命令,但是 make 失败了,可能是一些非常简单的问题 :) - Kimvais阅读/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
功能的函数。
system("cat /proc/cpuinfo | grep processor | wc -l");
这将打印出您系统中的CPU数量。如果您想在程序中使用此系统调用的输出,则可以使用popen系统调用。
cat /proc/cpuinfo | grep -w cores | sed -e 's/\t//g' | awk '{print $3}' | xargs | sed -e 's/\ /+/g' | bc
nproc
cat
是没有意义的。以下代码可以正常工作:grep -m1 "cores" /proc/cpuinfo | tr -d '[a-z]:[:space:]'
。 - Yokai