如何使用C获取Linux中的CPU数量? [英] How to get the number of CPUs in Linux using C?
本文介绍了如何使用C获取Linux中的CPU数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有API可以获取Linux中可用的CPU数量? 我的意思是,不使用/proc/cpuinfo或任何其他sys-node文件...
Is there an API to get the number of CPUs available in Linux? I mean, without using /proc/cpuinfo or any other sys-node file...
我已经使用sched.h找到了该实现:
I've found this implementation using sched.h:
int GetCPUCount()
{
cpu_set_t cs;
CPU_ZERO(&cs);
sched_getaffinity(0, sizeof(cs), &cs);
int count = 0;
for (int i = 0; i < 8; i++)
{
if (CPU_ISSET(i, &cs))
count++;
}
return count;
}
但是,使用通用库还没有更高的层次吗?
But, isn't there anything more higher level using common libraries?
推荐答案
#include <stdio.h>
#include <sys/sysinfo.h>
int main(int argc, char *argv[])
{
printf("This system has %d processors configured and "
"%d processors available.\n",
get_nprocs_conf(), get_nprocs());
return 0;
}
https://linux.die.net/man/3/get_nprocs
这篇关于如何使用C获取Linux中的CPU数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文